Search code examples
iosswiftalamofire

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?


Solution

  • 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*/)