Securing TabBar Items Using Protocol Extensions

A very common requirement in iOS apps is to validate if the user is already logged in or not. In a tabbed application, the tab items may be visible to the user but the content is not displayed until the user is logged in.

In the screenshot below, My Receipts and My Bills are supposed to be secure tab. This means that if the user is not logged in then by selecting one of those tabs the user is presented with a login screen.

The most obvious solution is to put the validation code in the corresponding tab item view controllers. Here is the implementation for MyReceiptsViewController.

This will work fine but now we have to repeat the same code for MyBillsViewController and all the other controllers that needs to display a login screen before the user can view them. Let’s see how we can create a much better more it using protocol extension.

LoginHandler Protocol

The LoginHandler protocol consists of a single function called validate. This function is responsible for determining if the user is currently logged in or not.

We have extended the LoginHandler protocol to give a default implementation as shown below:

The actual implementation of the validate function is not important right now so we have simply returned false indicating that the user is not logged in.

Now, every controller that needs to validate whether the user is logged in or not is going to use the LoginHandler protocol as shown below:

We still need to invoke the validate function. The best place is from when the TabBar item is selected.


Instead of putting the responsibility of showing the LoginViewController to the individual view controllers we have created a base TabBarController which will handle the selection of TabBar items.

We check if the controller conforms to the LoginHandler, if it does not then we simply return true. If the controller does conform to the LoginHandler then we call the validate function. If the validate returns false then we finally show the user the LoginViewController, allowing them to log-in to the application.

If you like this post then you might be interested in checking out my course “A Complete Guide to Lean Controllers in iOS”. The course covers many useful architecture patterns to build better iOS applications. Receive a 74% discount, click on the following link:

iOS Developer, speaker and educator. Top Udemy and LinkedIn instructor. Lead instructor at DigitalCrafts.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store