0
votes

I am working on a code which has done by someone else. I am bit new to swift as well. The below code is my network layer which have been used by other controller files. My requirement is to retry the last network request once the token is expired. How can I integrate that inside of network layer itself ? When logging to the application I am calling the get token service for the firs time and saving it in the headers.

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

1 Answers

0
votes

I suggest you to user RequestRetrier class in Alamofire

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)
    })
}