Create a beautiful Network Layer With Swift

Ertem Biyik
2 min readMay 31, 2022

--

Barely all swift developers once upon a time face with a task of interacting with API’s. Have you ever wondered how to make it look and feel seamless?

Recently I’ve been working on swift-ethereum project: https://github.com/sparrowcode/swift-ethereum and wrote some cool stuff that I want to share with you guys. This article shows how to make a scalable, pretty Network Layer for your iOS app or swift package.

For this tutorial, I have chosen the Rick and Morty API (https://rickandmortyapi.com). It has 3 main routes:

So for tutorial purposes we will take the character’s route and play with it.

Service

Let’s create an enum with the baseURL inside it

RoutePrototcol

A type that confirms to this protocol will give us the stringValue which we add to baseURL and get the API endpoint. The method is the httpMethod being used for this request. You can also add httpHeaders property

CharacterRoute

Let’s create an enum that confirms to the protocol above:

From each of the cases we can get the stringValue which should be added to baseURL and httpMethod needed for request.

The character struct that I need looks like this:

The info struct:

NetworkManager

This is where the magic happens. This class will manage encoding, sending, receiving and decoding data from/to server.

We provide an initialization for class with baseURL, a session for dataTask calls and a concurrent queue to make our manager thread safe. We also call finishTasksAndInvalidate() inside a deinit block to finish and stop all outgoing requests after an instance of our manager is being deinitialized.

Next let’s take a look at sendRequest method: it is a generic function, which generates a request based on given inputs, sends it and decodes a response. We have two of them, because the params field is generic and for some requests we don’t need any httpBody.

Now we can add an instance of NetworkManager to the Service.

We also need to implement methods inside CharacterRoute using manager:

That’s it! Take a look, how beautiful and logical it looks when you use it:

So what are the beauties of this network layer?

  • Quick fixes if the API changed: if the URL of some endpoint or the params needed for request changes, you always know where and what to fix
  • Scalability: if a new endpoint is added just write new case to enum, the compiler will force you to write stringValue and method
  • Independence of NetworkManager: any params can be sanded/received due to its generic nature

That’s it! Thank you for reading, have a nice one)

--

--