Managing Network States With Protocol Extensions

Content? Loading? Error? Empty? Lost…

Today morning I opened the Apple’s music app to soothe my ears with some songs. But of course, as an iOS developer I was more drawn to examine the functionality of the app instead. What I found was the subtle ways in which the app handles state changes.

Content, Loading, Error and Empty states

So, it drew me to find the best ways in which we could handle network states in our applications.
Let’s say we’re building an app which manages four states, namely:
1. Content: The data is presented to the user
2. Loading: The data is being loaded over network
3. Error: Error encountered while loading data over network
4. Empty: No data available to be displayed to the user
The questions which arises are: Is my code reusable? Do I follow the DRY principle? What if I have different methods to manage states in different classes? Is code refactoring easy?
If your answer is ‘No’, you can refer to the ‘The Solution’ or else have your spaghetti.

The Solution

At WWDC 2015, Apple introduced Protocol-Oriented Programming. With it came the most powerful feature: Protocol Extensions.
Wait, what did you say? Now, what the hell is protocol extension. If you are new to the concept, please refer to the links:

Quick look at the Demo

Let’s start with Protocol

We have a protocol named ViewStateProtocol:

Let’s talk about it. We have a state manager class instance (class which manages adding and removing views), loading, error and empty views, an error message and a method declaration addView which takes States Type as a parameter(an enum containing the various states)

Now, let’s have some magic with protocol extensions.
First, we created a single instance of State manager class which takes care of adding and removing views. Then, we create loading, error and empty view objects.

Awesome! But, we still need to add these views to our view controller’s view. So, how to do that? Not a problem, we have state managers to our rescue. State Manager class will take care of adding these views.

Yay! We did it. But wait, where’s our State Manager class. Let’s have a look at it too…

So, we’ve the default implementation for all the views. But how do we implement it? Ever wondered?

Implementation of protocol

Our view controller is going to implement the ViewStateProtocol and call the methods whenever it needs to display the views.

Any view controller that is concerned with managing network related states can implement the ViewStateProtocol and reuse all the code. As simple as this 🙂

Wrap up

Protocol Extensions allow us to have mixin like pattern. Its advantageous for code reusability and maintainability.

This github repository has a demo application

Lubaba Hasnain