感谢您关注我的问题。我明白了。我必须使用Alamofire Swift刷新JWT令牌。令牌每30分钟过期一次,因此当我进行POST或GET请求时,令牌可能过期并遇到错误代码(状态代码)500。然后,我必须调用刷新令牌API并从服务器获取新令牌,然后再次调用以前的API 。我的问题是在获取新令牌后如何调用失败的API。希望可以通过更好的解决方案对此有所帮助。提前致谢。
当前状态。
API请求方法,
func statusStaffCheckInOut(completion: @escaping(Bool)->Void){
guard let userID= userLoginModel.user?.id else{ return }
guard let jwtToken = userLoginModel.jwt else{ return }
let x_headers = ["x-authorization": "\(jwtToken)","id":"\(userID)"]
Alamofire.request("\(BASE_MIDDLEWARE_URL)/url",method: .get, encoding: JSONEncoding.default , headers: x_headers).validate(statusCode: 200..<300)
.validate(contentType: ["application/json"]).responseJSON { response in
// print("Request: \(String(describing: response.request))")
// response serialization result
if let json = response.result.value as? [String:Any]{
userLoginModel.staffcheckincheckout?.setValuesForKeys(json)
completion(true)
}else {
if let statusCode = response.response?.statusCode{
print("status code \(statusCode)")
if statusCode == 500{ ///Check 500 Error code
print("Status code ***\(500)***")
///Refresh taken call
self.refreshJWTToken(trigeredURL: "url"){(response) in
}
}
}
completion(false)
}
}
}
刷新令牌方法:
//MARK:- Token Refresh
func refreshJWTToken(trigeredURL: String,completion: @escaping([[String:Any]],Bool)->Void){
guard let userID = userLoginModel.user?.id else{ return }
let url = "\(BASE_MIDDLEWARE_URL)/url?id=\(userID)"
Alamofire.request(url,method: .get, encoding: JSONEncoding.default).validate(statusCode: 200..<300)
.validate(contentType: ["application/json"]).responseJSON { response in
if let json = response.result.value as? String{
userLoginModel.jwt = json
print("Refreshed JWT: \(json)")
completion([["Message":"Success"]],true)
}else {
completion([["Message":"Faild"]],false)
}
}
}
答案 0 :(得分:1)
我已修改您的请求以适应您的需求。
枚举:
enum APIResult<T> {
case success(T)
case failure(NSError)
}
API请求方法:
func statusStaffCheckInOut(callback: @escaping(APIResult<Void>) -> Void){
guard let userID= userLoginModel.user?.id else{ return }
guard let jwtToken = userLoginModel.jwt else{ return }
let x_headers = ["x-authorization": "\(jwtToken)","id":"\(userID)"]
Alamofire.request("\(BASE_MIDDLEWARE_URL)/url",method: .get, encoding: JSONEncoding.default , headers: x_headers).validate(statusCode: 200..<300)
.validate(contentType: ["application/json"]).responseJSON { response in
// print("Request: \(String(describing: response.request))")
// response serialization result
if let json = response.result.value as? [String:Any]{
userLoginModel.staffcheckincheckout?.setValuesForKeys(json)
// completion(true)
callback(.success(()))
}else {
if let statusCode = response.response?.statusCode{
print("status code \(statusCode)")
if statusCode == 500 { ///Check 500 Error code
print("Status code ***\(500)***")
///Refresh token call
self.refreshJWTToken(trigeredURL: "url"){ result in
switch result {
case .success(_):
self.statusStaffCheckInOut(){ result in
switch result {
case .success(()) : callback(.success(()))
case let .failure(error): callback(.failure(error))
}
}
case let .failure(error):
callback(.failure(error))
}
}
}
}
callback(.failure(NSError(domain: "Error", code: -1, userInfo: [NSLocalizedDescriptionKey: "Invalid authorization"])))
}
}
}
刷新令牌方法:
//MARK:- Token Refresh
func refreshJWTToken(trigeredURL: String,callback: @escaping(APIResult<Void>) -> Void){
guard let userID = userLoginModel.user?.id else{ return }
let url = "\(BASE_MIDDLEWARE_URL)/url?id=\(userID)"
Alamofire.request(url,method: .get, encoding: JSONEncoding.default).validate(statusCode: 200..<300)
.validate(contentType: ["application/json"]).responseJSON { result in
switch response.result {
case let .success(value):
if let json = value as? String{
userLoginModel.jwt = json
print("Refreshed JWT: \(json)")
callback(.success(()))
}else {
callback(.failure(NSError(domain: "Error", code: -1, userInfo: [NSLocalizedDescriptionKey: "Invalid authorization"])))
}
case let .failure(error):
callback(.failure(NSError(domain: "Error", code: -1, userInfo: [NSLocalizedDescriptionKey: "Invalid authorization"])))
}
}
}
我将通用返回用于api结果。您可以在成功回调中传递任何内容。