Erik
Erik

Reputation: 2409

Call a function before/after each Alamofire request

I'd like to know if there is anyway to implement something akin to middleware using Alamofire and iOS.

I've got a slew of API calls that are all pretty similar, and they all require a valid json web token for authentication. I want to perform the same validation before every API call, or alternately take the same corrective action when any API call fails. Is there a way I can configure it so that I don't have to copy and paste the same chunk of code onto the beginning or end of all of the API calls?

Upvotes: 0

Views: 1889

Answers (2)

Zac Kwan
Zac Kwan

Reputation: 5747

If you are trying to attach the a common header to all call, you can set it using the Alamofire.manager.All Alamofire.request use a common shared instance of Alamofire.manager

var defaultHeaders = Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders ?? [:]
defaultHeaders["Accept-Language"] = "zh-Hans"

let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = defaultHeaders

let manager = Alamofire.Manager(configuration: configuration)

For auth token, i do it like this in a network class that perform all my requests.

func authHeaders() -> [String: String] {
    let headers = [
        "Authorization": "Token \(UserManager.sharedInstance.token)",
    ]
}
Alamofire.request(.GET, "https://myapi/user", headers: authHeaders())
     .responseJSON { response in
         debugPrint(response)
     }

Upvotes: 1

Yannick
Yannick

Reputation: 3278

Wrapper Class

You can create a wrapper for your request.

class AlamofireWrapper {
    static func request(/*all the params you need*/) {
        if tokenIsValidated() { //perform your web token validation
            Alamofire.request//...
            .respone { /*whatever you want to do with the response*/ }
        }
    }
}

You can use it like this wihtout having to copy and paste the same code again.

AlamofireWrapper().request(/*params*/)

Extension

This is not tested. You can add an extension to Alamofire

extension Alamofire {
    func validatedRequest(/*all the params you need*/) {
        if tokenIsValidated() { //perform your web token validation
            Alamofire.request//...
            .respone { /*whatever you want to do with the response*/ }
        }
    }
}

and use it like this

Alamofire.validatedRequest(/*params*/)

Upvotes: 2

Related Questions