Router pattern with Alamofire’s URLRequestConvertible protocol

Mohammadreza Khatibi
2 min readJul 14, 2021

If you are an iOS developer and have been developing for some time, your app probably needs to communicate with API over the network and retrieves data from a server. This tutorial teaches about the Alamofire router pattern, which helps us have a clean network layer and avoid duplicating code.

Alamofire

Alamofire is an HTTP networking library written in Swift for iOS, iPadOS, and macOS. It provides an elegant interface on top of Apple’s Foundation networking stack that simplifies several common networking tasks.

What is Alamofire Good For?

Why do you need Alamofire at all? Apple already provides URLSession and other classes for downloading content via HTTP, so why complicate things with another third-party library?
The short answer is Alamofire is based on URLSession, but it frees you from writing boilerplate code, which makes writing networking code much easier. You can access data on the Internet with minimal effort, and your code will be much cleaner and easier to read.

Here’s an example of the same networking operation with Alamofire’s request function:

If you used Alamofire before, you probably created an API manager or some network model in your apps which causes code duplication because we used to write the URL path, HTTP method, and query parameters for each request.
As the app size grows, it’s essential to use some common patterns for building the network stack. But how can we do that? The answer is using URLRequestConvertible protocol and Router design pattern.

The router is responsible for creating the URL requests so that our API manager (or whatever makes the API calls) doesn’t need to do that.

URLRequestConvertible

URLRequestConvertible is protocol, and it has a single requirement, asURLRequest(), which helps construct a URLRequest.

Ok, let's start.

To start, we will declare a router. It will be an enum with a case for each type of call we want to make.

  1. First, add a case for each URLRequest endpoint. Swift enums can have arguments, and we can pass our data to the router.
  2. Define the endpoint for each URLRequest.
  3. Add http method like .get, .post, .delete, .put… for each case.
  4. You can add parameters property to set API parameters.
  5. To conform URLRequestConvertible protocol we must add asURLRequest() function to the router.
  6. In the asURLRequest function, define URL as BaseURL and append path as request endpoint.
  7. Define request as URLRequest.
  8. Add HTTP method to the request.
  9. Optionally, we can add a timeout to the request.
  10. Finally, return URLEncoding with the request I define earlier.

Done, the login router was created, and now time to use it.

That’s all. As you can see, we no longer have to declare URL, query parameters, and headers locally for each API call.

--

--