Swift Network Layer — An Update

Malcolm Kumwenda
2 min readApr 24, 2018

Firstly I would like to express my gratitude to everyone who clapped, commented on my previous post Writing a Network Layer in Swift: Protocol-Oriented Approach 😁👏🏾. After some feedback in the comments and more research, I thought it would be beneficial to address the suggested improvements in this post.

We have two simple modifications that can be made to the project that can improve its functionality.

URLSession

In our previous implementation of URLSession, we made use of URLSession.shared. This code works but it is not optimal. Every time we make a request we instantiate a new session. It is advised to have one URLSession and multiple tasks.

Previous implementation.

Previous implementation.To fix this we will instantiate a session when we create our Router using the default configuration. There are 3 different types of configurations you can use to create your session. I advise you to read this article from Raywenderlich.com.

Updated implementation

With this code we create one session and have multiple tasks. An extra advantage here is that we can tweak the router initialisation code to have a session parameter which we will make writing our tests much easier by making use of a mock.

URLQueryItem

For this one I would like to thank Koen Punt and ilya stroganov for their comments. I was not aware of the fact that URLQueryItem already encodes our parameters.

Previous implementation.

This is a quick update just remove .addingPercentEncoding(withAllowedCharacters: .urlHostAllowed). And done.

Updated implementation.

Conclusion

I’ll never act like I know everything. I am learning all this as I write on Medium. There are times when I have referenced my own posts to remind how to achieve anything. Having a life long learner attitude is what will make one grow. I like to share my discoveries and hopefully help someone whilst at it.

With that said if there are any topics you would maybe like me to make a post on please mention in the comments. Thank you once again for all the 👏🏾. Keep learning and thinking in Swift ⚡️.

--

--