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.

Quick look at the Demo

Let’s start with Protocol

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.