IOS developer based in barcelona.

Interceptors in your URLRequest

I'm creating a minimal API for Slack, it basically sends messages to users, private channels and public channels. In every request I need to add the same parameter: a valid token. Without this token my requests will fail.

In this case I need a valid token, but in other scenarios you could need a request with custom headers or you need to add some responsibilities in a request that doesn't fit in your current class. For that purposes, you could use Interceptors to capture this request before (or after). 

Alamofire has a request interceptor, it's called AccessTokenAdapter and it has a method with a unique parameter. The main idea is receiving a Request and update some values or add a new ones and finally return the modified Request

The code below shows an example adding a new value in HTTPHeaderField to get authentication from server.

class AccessTokenAdapter: RequestAdapter {
    private let accessToken: String

    init(accessToken: String) {
        self.accessToken = accessToken
    }

    func adapt(_ urlRequest: URLRequest) throws -> URLRequest {
        var urlRequest = urlRequest

        if let urlString = urlRequest.url?.absoluteString, urlString.hasPrefix("https://httpbin.org") {
            urlRequest.setValue("Bearer " + accessToken, forHTTPHeaderField: "Authorization")
        }

        return urlRequest
	}
}

Now we need to instantiate our custom interceptor and assign to the sessionManager's adapter. In every API call, the access token will be added magically in our request's header.

let sessionManager = SessionManager()
sessionManager.adapter = AccessTokenAdapter(accessToken: "1234")

sessionManager.request("https://httpbin.org/get")

Conclusion

A nice way to send the same parameters over and over again is through Interceptors.  Besides, you can check with pattern matching the endpoint to add different values in different scenarios. For example, in some API calls you must send a token as a parameters instead of adding it in the header field.

I'm all ears to know your feedback, thanks for reading! 😃

Create NSTableView programatically without Storyboards

Command-line scripts in Swift - Swift Package Manager