now I'm working on an iOS application in Swift 4. Here I'm using Alamofire to integrate the API calls. I need to integrate the right way to auto-refresh the authentication token and retry the previous API calls. I'm storing the authentication token once I logged in successfully. So after login, in each API, I'm appending the token in the header part. And when if the token is expired I will get 401. That time I need to auto-refresh the authentication token and recall the same API again. How can I do that? I checked in the Stackoverflow, but I didn't get any solution.
Here's my API Call,
import Foundation
import Alamofire
import SwiftyJSON
class LoveltyAPI {
let loveltyURL = Bundle.main.object(forInfoDictionaryKey: "APIUrlString") as! String // Main URL
let buildVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String //infoDictionary?["CFBundleShortVersionString"] as AnyObject
weak var delegate:LoveltyProtocol?
func get_profile(app_user_id:String, token:String) {
let urlString = "\(loveltyURL)\(get_profile_string)?app_user_id=\(app_user_id)"
let headers = ["Content-Type":"application/json","X-Requested-With":"XMLHttpRequest", "Authentication":"Token \(token)"]
Alamofire.request(urlString, method: .get, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
switch response.result {
case .success:
let swiftyJsonVar = JSON(response.result.value!)
switch response.response?.statusCode {
case 200, 201:
self.delegate?.getUserProfile!(response: swiftyJsonVar["data"].dictionaryObject as AnyObject)
case 401:
self.delegate?.tokenExpired(response: tokenExpired as AnyObject)
case 404:
self.delegate?.serviceError!(response: swiftyJsonVar["message"] as AnyObject)
case 422:
self.delegate?.serviceError!(response: swiftyJsonVar["error"] as AnyObject)
case 503:
self.delegate?.appDisabled(response: swiftyJsonVar.dictionaryObject as AnyObject)
default:
self.delegate?.serviceError!(response: self.serverError as AnyObject)
}
case .failure(let error):
self.delegate?.serviceError!(response: self.serverError as AnyObject)
}
}
}
}
Please help me. If you can explain with my code, it would be very nice.