如何在 Alamofire 中刷新 JWT 令牌状态代码 500 Swift
How to refresh JWT token status Code 500 in Alamofire Swift
感谢您查看我的问题。我说到点子上了。我必须使用 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)
}
}
}
我已经修改了您的请求以满足您的需要。
枚举:
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"])))
}
}
}
我使用通用 return 作为 api 结果。您可以在成功回调中传递任何内容。
感谢您查看我的问题。我说到点子上了。我必须使用 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)
}
}
}
我已经修改了您的请求以满足您的需要。
枚举:
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"])))
}
}
}
我使用通用 return 作为 api 结果。您可以在成功回调中传递任何内容。