Press "Enter" to skip to content

Charming the VIPER

While writing an application from scratch coming up with the right architecture for it holds great value. It usually depends on the scope of the application. For instance, if it’s a small scale application with a limited scope then going with an architecture which is scalable would be an overhead.

VIPER is a flexible and scalable architecture that works on SOLID principles. It supports the theory of Clean Architecture that also emphasises on having the app’s structure divided into multiple layers. In VIPER, responsibilities are segregated and broken down into separate components.

VIPER stands for:

View: In simple words, View Controller is your View. It interacts with the Presenter and it tells the View what to show and what not to.

Interactor: It is where all the business logic resides. It interacts with the Presenter to and fro for any updates that a Presenter requests. It also interacts with Entities for any data.

Presenter: It acts as a gateway between all the components. It communicates with Interactor for the data, with View for actions and updating, with Router for routing to screens.

Entity: It’s just a fancy term for a data model. It may also contain data sources or repositories.

Router/WireFrame: It’s sole purpose is to hold all the navigation logic.

VIPER Architectural Diagram

To get a better grasp on it. Let’s understand it by an example. To follow along, clone or download the sample project from here.

Don’t let this bother you.

Open the Starter Project. You’ll see a storyboard consisting of two controllers. Something like this:

Let’s get cracking with some code now.

The app is simple. You can add/edit/delete any task in it and by tapping on the cell view the full details on the next screen.

First create a new group under TaskLogger -> Entities. Inside Entities, create a file and name it as TaskItem.

The model consists of a title and its description which is optional for an specific task.

Let’s move on, and create another class under the Entities and name it TasksManager. That will be a singleton just to hold the data through a session. (Since the main focus of this tutorial is to understand the VIPER architecture. Let’s keep things simple.)

This class maintains an array of TaskItem for a session.

Let’s now work on adding and displaying some tasks in the list. Create a group and name it TaskList. Under that create a group and name it Protocols. Inside it create a file and name it TaskListProtocols (TaskList->Protocols->TaskListProtocols). And paste the following code in it.

This might looks somewhat confusing. But bear with me. It’ll all start to make sense in a little while. ;]

Create three more groups inside the TaskList group. Naming them: Interactor, Presenter,  and Router with files inside named TaskListInteractorTaskListPresenter, and TaskListRouter respectively, and also create a group View under TaskList and move your TaskListViewController under it.
Your folder structure would look something like this:

The purpose of creating these files is to implement all the protocols written in the TaskListProtocols file.

Let’s start by implementing the Interactor first. Open your TaskListInteractor and paste the following code:

Before going any further. Let’s understand the difference between TaskListPresenterToInteractorProtocol and TaskListInteractorToPresenterProtocolTaskListPresenterToInteractorProtocol is the Presenter asking the Interactor to do something. For instance, save a task or fetch the list of tasks. Whereas, TaskListInteractorToPresenterProtocol is the Interactor informing the Presenter back that it has done its part.

//1 – Object for Interactor to inform back to Presenter.

//2 – Object and array of all the tasks shared across the app using a single object.

//3 – Sends all the tasks to Presenter.

//4 – Saves a tasks.

//5 – Updates a task on a certain index.

//6 – Deletes a task from a certain index.

Open the TaskListPresenter and add the following code in it.

//1 – view on which this (TaskListViewProtocol) protocol is implemented to listen to the data changes. The property of interactor here is the one which was implemented above. The reason of creating this property here is to pass data from this Presenter to the Interactor implemented earlier. The router property is for routing from the view assigned to it.

//2 – Calls the interactor to fetch tasks.

//3 – Tells the router to show a particular task.

//4, 5, 6 – Add, update or delete a task using the interactor.

To give updates to the Presenter from the Interactor. Inside the same file, do:

//1, 2, 3 – Fetch the latest task, after a change is done.

//4, 5 – Update the UI.

And now in your TaskListRouter.

For now this chunk of code simply is for navigating to the detail screen.

At this point the Presenter, Interactor and Router are all set up for the TaskListViewController.

After seeing all this code and not yet being able to add a task, probably would have made you wonder.

Hang in there lad! You’re almost there.

Adding a Task

Inside your TaskListViewController create two properties.

and also add a function.

Above function creates an alert controller with textfields and passes the TaskItem to the presenter once Save is tapped.

Now inside your @IBAction addTask.

Change your UITablviewDataSource functions to make it look like:

Conform to the TaskListViewProtocol.

It’s time to setup presenter and the rest of the dependencies i.e interactor, view, and router.

Call the above method in viewDidLoad. The only reason these dependencies are injected here because this controller is not loaded inside the didFinishLaunchingWithOptions of the AppDelegate otherwise this would have been moved to the TaskListRouter. Don’t get confused this all will make sense soon.

After that build and run it and let’s test it by adding a task. You’ll see something like this:

Tap on +.


Add a title for e.g: “Learn Django” and in the description add “In the next 6 months” then tap on Save. Your task will be added as you can see below:

You have successfully added your first task to the list. Let’s now look at how the update and delete is done.

Updating and Deleting a Task

Updating:

Add the following method inside your TaskListViewController.

This method opens the task you want to edit in an alert controller with textfields like the one you have for adding a task. Moreover, implement the editActionsForRowAt of the UITableViewDelegate and make it look like this:

Deleting:

For the deleting part. Update your editActionsForRowAt to look something like:

Build and run. Since there is no persistence layer so you’ll have to add a task again. Add the same task again first. Then swipe from right to left. You’ll see two buttons Edit and Delete.

Tap on Edit and change the description to something like “In the next 6 months because I have made a huge mistake.” (No offense intended if you’re a python developer. ;])

Tap on Update and you’ll see the change instantly.

Test the delete functionality as well by swiping from right to left. Tap on the Delete button and you shouldn’t see anymore task in your list.

Let’s now move to the detail screen part. Create a group and name it TaskDetail inside it create groups View, Protocols, Presenter, Interactor, and Router. Furthermore, move the TaskDetailViewController inside the View group and create files TaskDetailProtocolsTaskDetailPresenterTaskDetailInteractor, and TaskDetailRouter respectively. Your hierarchy should look similar to the one above in the TaskList module.

Open your TaskDetailProtocols and paste the following code:

Here there was no need to create an interactor protocol which informs back to the presenter because this screen just shows data and no data manipulation is done here.

Open your TaskDetailPresenter and write the following code:

//1 – Passes the task to the view.

Now in your TaskDetailInteractor.

//1 – Holds the passed in task.

In your TaskDetailRouter.

//1 – Returns the object of TaskDetailViewController with all the dependencies injected i.e presenter, view, interactor and the task.

Open TaskListRouter and update presentTaskListDetail to:

Open TaskDetailViewController and add the following property:

and call its method in the viewDidLoad:

and also implement the TaskDetailViewProtocol:

Now head back to TaskListViewController and add didSelectRowAt of the UITableViewDelegate with the following code:

Run the app, add the task again and tap on it. You’ll see the detail screen as follows:

Give yourself a pat on the back. You’ve successfully made a TaskLogger app using the VIPER architecture.

 

What to do now?

By the end of this tutorial. You must have a good idea about how VIPER works. You can find the complete source code in the link attached in the start. There are also links to some good reads you should have a look at.

If you’re looking for something on using VIPER in Android. You should check out this:

If you have any questions or queries please feel free to leave it in the comment section below.

Author: Aaqib Hussain

Aaqib is an enthusiastic programmer with the love of Swift and anything that looks like Swift i.e Kotlin. He loves writing code in Swift, and exploring new technology and platforms. He likes to listen to old music. When he is not writing code, he’s probably spend his time watching movies, tv-shows or anime, or either doing some research for writing the next article. He started Kode Snippets in 2015.

One Comment

  1. Ajmal
    Ajmal October 23, 2018

    nice article Aqib. Can you please elaborate what problem does VIPER solve which MVVM doesn’t. Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *