现在我正在使用 Swift 4 开发一个 iOS 应用程序。这里我使用 Alamofire 来集成 API 调用。我需要集成正确的方法来自动刷新身份验证令牌并重试以前的 API 调用。成功登录后,我将存储身份验证令牌。因此,登录后,在每个 API 中,我将令牌附加到标题部分。如果令牌过期,我将得到 401。那时我需要自动刷新身份验证令牌并再次调用相同的 API。我怎样才能做到这一点?我检查了 Stackoverflow,但没有得到任何解决方案。
这是我的 API 调用,
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)
}
}
}
}
请帮我。如果你能用我的代码解释一下,那就太好了。