1

感谢您查看我的问题。我进入正题。我必须使用 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)
                }
        }
    }
4

1 回答 1

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 结果使用通用返回。您可以在成功回调中传递任何内容。

于 2018-08-10T18:00:02.003 回答