我正在使用Alamofire
集成 API 调用、处理错误代码和特别是状态代码错误,例如401
和403
. 我还创建了该getRefreshToken()
函数,如果出现错误,它将刷新令牌。
我面临的问题Alamofire.retryCount
并以正确的方式重复请求?我看过不同的参考资料,但我无法弄清楚我是如何整合到我的主要方法中的。
更新:添加getRefreshToken()
代码。
我的代码:
@objc private func getDataFromWeb(params:NSMutableDictionary,
callback:@escaping (_ success:Bool, _ result:Any?)->(Bool)) -> Void {
var method = HTTPMethod.get
var encoding = URLEncoding.default as ParameterEncoding
if(params["Method"] as! String == "POST"){
method = HTTPMethod.post
encoding = Alamofire.JSONEncoding.default
}
Alamofire.request(url,
method:method,
parameters:pr,
encoding:encoding,
headers:[ "Accept":"application/json", "Authorization":"Bearer \(token ?? "")"])
.downloadProgress(closure: { (progress) in
//progress closure
})
.validate(statusCode: 200..<300)
.response { response in
print(response.error?.localizedDescription)
var code = response.response?.statusCode
if code == 401 || code == 403{
self.getRefreshToken() // calling refresh token method
} else {
if(callback(response.data?.count != 0, response.data)){
}
}
}
}
getRefreshToken 函数:
func getRefreshToken() {
DataProvider.main.serviceLogin(username:User, password:Pass, firmNo: FirmId , callback:{success, result in
do{
if(success){
let model = try JSONDecoder().decode(Login.self, from: result as! Data)
if model.isSuccess == true {
DataProvider.main.token = model.token
}
return true
} else{
return false
}
}catch let e {
print(e)
return false
}
})
}
参考:
https://stackoverflow.com/questions/58496713/retry-the-old-request-with-new-refresh-token-in-swift-alamofire
https://stackoverflow.com/questions/52287882/right-way-to-refresh-the-token