在Swift + Alamofire中使用新的刷新令牌重试旧请求

时间:2019-10-22 03:32:48

标签: swift alamofire refresh-token

我正在编写别人编写的代码。我也很新,也很快。以下代码是我的网络层,该网络层已被其他控制器文件使用。我的要求是令牌过期后重试最后一个网络请求。如何将其集成到网络层本身中?登录到应用程序时,我将在第一时间调用get令牌服务并将其保存在标题中。

import UIKit
import Alamofire
import Timberjack

class NetworkManager: NSObject {

var token: String!
var APISecret = ""
var basicAuth = "Basic ZXh0X3dlYjpuMWlmP2NlP3F1ZW45SA=="
var manager: SessionManager?

static let sharedManager = NetworkManager()

var staging = "END_POINT_STAGING"
var production = "END_POINT_PRODUCTION"      
var domain          = AppDelegate().staging
var putDomain       = "\(AppDelegate().domainType)/END_POINT."

private override init() {
    super.init()
    self.initSetup()
}

func initSetup() {
    self.manager = Alamofire.SessionManager.default
}

func httpHeaders() -> HTTPHeaders? {
    var headers = HTTPHeaders()
    guard let token = AppManager.sharedManager.token() else {
        return headers
    }
    headers.updateValue("Bearer \(token)", forKey: "Authorization")
    return headers
}

func httpBasicAuthHeaders() -> HTTPHeaders? {
    let headers: [String: String] = [
        "Content-type": "application/json",
        "Authorization": basicAuth
    ]
    return headers
}

func alamofireRequest(domain: String, method: HTTPMethod, parameters: Parameters?, success: @escaping (_ json: [String: AnyObject]) -> (), failure: @escaping (_ error: Error) -> ()) {
    manager?.request(domain, method: method, parameters: parameters, encoding: URLEncoding.default, headers: httpHeaders())
        .responseJSON(completionHandler: { (response) in
            guard let error = response.result.error else {
                let allData = response.result.value as! [String: AnyObject]
                success(allData)
                return
            }
            failure(error)
        })
}

func alamofireRequestForPatchRequests(domain: String, method: HTTPMethod, parameters: Parameters?, success: @escaping (_ json: [String : AnyObject]) -> (), failure: @escaping (_ error: Error) -> ()) {
    manager?.request(domain, method: method, parameters: parameters, encoding: JSONEncoding.default, headers: httpHeaders()).responseJSON(completionHandler: { (response) in
        guard let error = response.result.error else {
            let allData = response.result.value as! [String : AnyObject]
            success(allData)
            return
        }
        failure(error)
    })
}

func alamofireJSONRequest(domain: String, method: HTTPMethod, headers: [String: AnyObject?], parameters: Parameters?, success: @escaping (_ json: [String: AnyObject]) -> (), failure: @escaping (_ error: Error) -> ()) {

    manager?.request(domain, method: method, parameters: parameters, encoding: URLEncoding.default, headers: httpBasicAuthHeaders()).responseJSON(completionHandler: { (response) in
                        guard let error = response.result.error else {
                            let allData = response.result.value as! [String : AnyObject]
                            success(allData)
                            return
                        }
                        failure(error)
                     })
}

func receivePostDataFor(_ command:String, parameters:AnyObject?, success:@escaping (_ json: AnyObject) -> Void, failure:@escaping (_ json: AnyObject?) -> ()) {
    let headers: [String: AnyObject?] = [:]
    return alamofireJSONRequest(domain: domain + command, method: .post, headers: headers, parameters: parameters as! Parameters?, success: {(json) in
           return success(json as AnyObject)
    }, failure: {(error) in
        failure(error as NSError)
    })
}

func receivePatchDataFor(_ command:String, parameters:AnyObject?, success:@escaping (_ json: AnyObject) -> Void, failure:@escaping (_ json: AnyObject?) -> ()) {
    return alamofireRequestForPatchRequests(domain: domain + command, method: .patch, parameters: parameters as! Parameters?, success: {(json) in
        return success(json as AnyObject)
    },  failure: {(error) in
        failure(error as NSError)
    })
}

func receiveGetDataFor(_ command:String, parameters:AnyObject?, success:@escaping (_ json: AnyObject) -> Void, failure:@escaping (_ json: AnyObject?) -> ()) {
    return alamofireRequest(domain: domain + command, method: .get, parameters: parameters as! Parameters?, success: {(json) in
        return success(json as AnyObject)
    },  failure: {(error) in
        failure(error as NSError)
    })
}

func receiveDeleteDataFor(_ command:String, parameters:AnyObject?, success:@escaping (_ json: AnyObject) -> Void, failure:@escaping (_ json: AnyObject?) -> Void) {
    alamofireRequest(domain: domain + command, method: .delete, parameters: parameters as! Parameters?, success: {(json) in
        success(json as AnyObject)
    },  failure: {(error) in
        failure(error as NSError)
    })
}

func receivePutDataFor(_ command:String, parameters:AnyObject?, success:@escaping (_ json: AnyObject) -> Void, failure:@escaping (_ json: AnyObject?) -> ()) {
    return alamofireRequest(domain: putDomain + command, method: .put, parameters: parameters as! Parameters?,
        success: {(json) in
            return success(json as AnyObject)
    },  failure: {(error) in
        failure(error as NSError)
    })
}

}

1 个答案:

答案 0 :(得分:0)

我建议您在Alamofire中使用RequestRetrier类

import UIKit
import Alamofire
import Timberjack

class OAuth2Handler: RequestAdapter, RequestRetrier {

func adapt(_ urlRequest: URLRequest) throws -> URLRequest {
    return urlRequest
}

public func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: RequestRetryCompletion) {
    if request.response?.statusCode == /* your expiry status code which you get from your server */ {
        // Implement your call to get new token from server && return the below completion handler
        completion(true, 1.0) // retry after 1 second
    } else {
        completion(false, 0.0) // don't retry
      }
    }
}





class NetworkManager: NSObject {

var token: String!
var APISecret = ""
var basicAuth = "Basic ZXh0X3dlYjpuMWlmP2NlP3F1ZW45SA=="
var manager: SessionManager?

static let sharedManager = NetworkManager()

var staging = "END_POINT_STAGING"
var production = "END_POINT_PRODUCTION"
var domain          = AppDelegate().staging
var putDomain       = "\(AppDelegate().domainType)/END_POINT."

private override init() {
    super.init()
    self.initSetup()
}

func initSetup() {
    let manager = Alamofire.SessionManager.default
    let retrier = OAuth2Handler()
    sessionManager.adapter = retrier
    sessionManager.retrier = retrier
    self.manager = manager
}

func httpHeaders() -> HTTPHeaders? {
    var headers = HTTPHeaders()
    guard let token = AppManager.sharedManager.token() else {
        return headers
    }
    headers.updateValue("Bearer \(token)", forKey: "Authorization")
    return headers
}

func httpBasicAuthHeaders() -> HTTPHeaders? {
    let headers: [String: String] = [
        "Content-type": "application/json",
        "Authorization": basicAuth
    ]
    return headers
}

func alamofireRequest(domain: String, method: HTTPMethod, parameters: Parameters?, success: @escaping (_ json: [String: AnyObject]) -> (), failure: @escaping (_ error: Error) -> ()) {
    manager?.request(domain, method: method, parameters: parameters, encoding: URLEncoding.default, headers: httpHeaders())
        .responseJSON(completionHandler: { (response) in
            guard let error = response.result.error else {
                let allData = response.result.value as! [String: AnyObject]
                success(allData)
                return
            }
            failure(error)
        })
}

func alamofireRequestForPatchRequests(domain: String, method: HTTPMethod, parameters: Parameters?, success: @escaping (_ json: [String : AnyObject]) -> (), failure: @escaping (_ error: Error) -> ()) {
    manager?.request(domain, method: method, parameters: parameters, encoding: JSONEncoding.default, headers: httpHeaders()).responseJSON(completionHandler: { (response) in
        guard let error = response.result.error else {
            let allData = response.result.value as! [String : AnyObject]
            success(allData)
            return
        }
        failure(error)
    })
}

func alamofireJSONRequest(domain: String, method: HTTPMethod, headers: [String: AnyObject?], parameters: Parameters?, success: @escaping (_ json: [String: AnyObject]) -> (), failure: @escaping (_ error: Error) -> ()) {

    manager?.request(domain, method: method, parameters: parameters, encoding: URLEncoding.default, headers: httpBasicAuthHeaders()).responseJSON(completionHandler: { (response) in
        guard let error = response.result.error else {
            let allData = response.result.value as! [String : AnyObject]
            success(allData)
            return
        }
        failure(error)
    })
}

func receivePostDataFor(_ command:String, parameters:AnyObject?, success:@escaping (_ json: AnyObject) -> Void, failure:@escaping (_ json: AnyObject?) -> ()) {
    let headers: [String: AnyObject?] = [:]
    return alamofireJSONRequest(domain: domain + command, method: .post, headers: headers, parameters: parameters as! Parameters?, success: {(json) in
        return success(json as AnyObject)
    }, failure: {(error) in
        failure(error as NSError)
    })
}

func receivePatchDataFor(_ command:String, parameters:AnyObject?, success:@escaping (_ json: AnyObject) -> Void, failure:@escaping (_ json: AnyObject?) -> ()) {
    return alamofireRequestForPatchRequests(domain: domain + command, method: .patch, parameters: parameters as! Parameters?, success: {(json) in
        return success(json as AnyObject)
    },  failure: {(error) in
        failure(error as NSError)
    })
}

func receiveGetDataFor(_ command:String, parameters:AnyObject?, success:@escaping (_ json: AnyObject) -> Void, failure:@escaping (_ json: AnyObject?) -> ()) {
    return alamofireRequest(domain: domain + command, method: .get, parameters: parameters as! Parameters?, success: {(json) in
        return success(json as AnyObject)
    },  failure: {(error) in
        failure(error as NSError)
    })
}

func receiveDeleteDataFor(_ command:String, parameters:AnyObject?, success:@escaping (_ json: AnyObject) -> Void, failure:@escaping (_ json: AnyObject?) -> Void) {
    alamofireRequest(domain: domain + command, method: .delete, parameters: parameters as! Parameters?, success: {(json) in
        success(json as AnyObject)
    },  failure: {(error) in
        failure(error as NSError)
    })
}

func receivePutDataFor(_ command:String, parameters:AnyObject?, success:@escaping (_ json: AnyObject) -> Void, failure:@escaping (_ json: AnyObject?) -> ()) {
    return alamofireRequest(domain: putDomain + command, method: .put, parameters: parameters as! Parameters?,
                            success: {(json) in
                                return success(json as AnyObject)
    },  failure: {(error) in
        failure(error as NSError)
    })
}