我正在与JWT代币和Alamofire一起使用Swift。我的问题是,当请求返回nil时,我希望request-method运行refreshToken()方法并重试HTTP请求。我的代码看起来像这样。我试图自己跑,但没有成功。 :(
// Internal method used for the HTTP methods
private func request<A>(resource: Resource<A>, method: Alamofire.HTTPMethod, parameters: [String:String], completion: @escaping (A?) -> ()) {
let requestUrl = self.baseurl.absoluteString + resource.url.absoluteString + "?token=" + self.loginManager.getFromKeychain().token!
Alamofire.request(requestUrl, method: method, parameters: parameters).response { response in
// Check if response need reauth
if(response.response?.statusCode == 401 || response.response?.statusCode == 400) {
self.refreshToken(completion: { result in
if(result) {
print("Token got refreshed")
// How do i make the request again?
}
})
}
guard let data = response.data else {
completion(nil)
return
}
completion(resource.parse(data as NSData))
}
}
答案 0 :(得分:1)
你的方法成为:
private func request<A>(resource: Resource<A>, method: Alamofire.HTTPMethod, parameters: [String:String], completion: @escaping (A?, error: Int?) -> ()) {
let requestUrl = self.baseurl.absoluteString + resource.url.absoluteString + "?token=" + self.loginManager.getFromKeychain().token!
Alamofire.request(requestUrl, method: method, parameters: parameters).response { response in
// Check if response need reauth
if(response.response?.statusCode == 401 || response.response?.statusCode == 400) {
completion(nil, response.response?.statusCode)
}
guard let data = response.data else {
completion(nil, nil)
return
}
completion(resource.parse(data as NSData, nil)
}
}
你的方法叫做
func myMethod(resource: Resource<A>, method: Alamofire.HTTPMethod, parameters: [String:String]) {
self.request(resource: resource, method: method, parameters: parameters) { (result, errorCode) in
if let errorCode = errorCode {
self.refreshToken(completion: { res in
if(res) {
print("Token got refreshed")
// How do i make the request again?
self.myMethod(resource: resource, method: method, parameters: parameters)
}
})
}
else if let result = result {
//ok got a result
}
}