Passing Data Between View Controllers using Delegate and Protocol for Beginners iOS - Swift 4

Astitv Nagpal
7 min readJul 10, 2018

--

Programming Language — Swift 4.1

I have seen a lot of people struggle when writing apps which requires passing data between different view controllers. Using segues is a convenient option but has its own complications. Especially in larger projects, it might not be the best option to go with.

Swift has a very cool concept of passing data using delegates and protocols. And in this article we will be building a basic iOS app to pass data from one view controller to another using delegate and protocol on a button click.

In our project, we will have two view controllers. From initial view controller on a button click we will transition to other view controller. In the other view controller we will have data to be passed onto the initial view controller. The data will be passed to the initial view controller on a button click using delegate and protocol using Swift.

Creating a New Project

We will start by opening Xcode and creating a new iOS project. We will select Single View App Template. In the next screen you can name your app according to your liking. I have named mine as SendingDataDelegate. Select a valid Team, your organization name and organization identifier in the respective fields. Most importantly in the language drop-down, select Swift. Select the directory where you want to save it and that’s it. You have setup your new Xcode Project !

Creating a New Project- Xcode

Adding the Required Files

In our project we will be requiring two view controllers namely FirstViewController.swift and SecondViewController.swift. You can rename the already created ViewController.swift file to FirstViewController.swift and create a new file under the same directory by right clicking on SendingDataDelegate folder and selecting new.

Adding files to Current Project

We need to select Cocoa Touch Class as the template for our second view controller class. For the new file give the class name as SecondViewController. Make sure that the new view controller is a sub-class of UIViewController. Also, since we are using Storyboards in our project, uncheck the also create XIB file option. Now save the file and you are all set.

Adding SecondViewController.swift class

Main.storyboard — Set Up

In our Main.storyboard file we will set up our UI for the iOS app. We will require two View Controllers. You can drag them from the Object Library on right bottom of the screen under Utilities section.

Selecting View Controller from Side Bar

After dragging the view controllers we will start with the first view controller. We will select it and register it with the identity inspector under the custom class section.

Registering the View Controller

Once it is set we will drag a label and a button on the FirstViewController. You can customize the UI elements as per your liking. We will follow the same steps for SecondViewController as well. Once both the view controllers are set, they should look like this:

FirstViewController — SecondViewController

Once the UI items are set we will create a segue from Get Data Button on FirstViewController to SecondViewController. This segue is used just to transition to SecondViewController and not pass any data. After dragging the segue on Button from FirstViewController to SecondViewController select segue kind as Present Modally.

Segue from FirstViewController to SecondViewController

After creating the segue we need to set the identifier for the segue to recognize it uniquely. To do this select the segue and on the right pane under attributes inspector, give a unique identifier for the segue. In my case I have named it getDataSegue.

Registering the Segue

All Right !! We are all set and our Main.storyboard should look something thing like this:

Final Main.storyboard

SecondViewController.swift — Set Up

After UI is complete we now start coding for our SecondViewController.swift file. First thing is to link all the UI elements to the view controller. For that we click option and drag and create respective outlets/actions. Here we have a TextField and a Button. For the TextField we will create an IBOutlet and name it dataToSendTextField. For the Button we will create an IBAction. Make sure to select Action in the connection drop down and name it sendDataButtonClicked.

After the UI elements are linked to the view controller the SecondViewController.swift will look like this (removed some extra unwanted code):

Now comes writing the main part of our iOS project. Setting up the protocol to be used by the view controllers to send and receive data. In SecondViewController.swift file above the class declare a protocol. Name the protocol MyDataSendingDelegateProtocol. Inside the protocol declare a function called sendDataToFirstViewController and have myData as a parameter of String type. This parameter will hold the data that we want to send to the FirstViewController.

After setting up the protocol we will declare a delegate variable of type MyDataSendingDelegateProtocol. This delegate variable is responsible to keep a track of the function and use that function to send data to FirstViewController.

We set the delegate variable as follows:

var delegate: MyDataSendingDelegateProtocol? = nil

Here, the delegate is of optional type because as of now we haven’t set it up. We just initialized it with nil.

Now, we will set up the action for the SendData button. Our aim is to send data from SecondViewController to FirstViewController on a button click. Under the sendDataButtonClicked IBAction function we will write our code to send the data.

Before sending the data by calling the function, we will check for two conditions.

First: Check if the delegate is not nil. If the delegate is nil then that means its not yet authorized to use this function to send data. Hence, its very important to first check nil for the delegate variable.

Second: Check if there is some data entered in the TextField. If there is no data entered then it doesn’t make sense to perform any action of sending data.

After these checks, we will call the function using our delegate variable. And inside the function we will pass our data to the parameter like so:

let dataToBeSent = self.dataToSendTextField.text

We pass the data to our delegate which in turn uses the function to pass it to another view controller. After calling the function we will dismiss our current view controller.

Once everything is set-up our final SecondViewController.swift sould look like this:

FirstViewController.swift — Set Up

After setting up our SecondViewController we come to our FirstViewController. First step will be setting up all the UI elements for FirstViewController. For this drag and drop the Label and set the IBOutlet.

No need to set an IBAction for the button as we already have set up the segue for the same. If you want to have some more functionality on clicking the button then you are free to set up an IBAction for the Receive Data button.

After setting up the IBOutlet for the label the FirstViewController.swift file should look like this (removed some extra unwanted code):

Now after UI elements are setup we start with the coding. The first and the foremost thing is for the FirstViewController to conform to the MyDataSendingDelegateProtocol that we had set up in SecondViewController. After you conform to it you will get an error. This error is expected and the compiler complains that we are not conforming to the protocol. This means we need to implement the delegate function that we had declared in the protocol.

Now we will confirm to the protocol by including the sendDataToFirstViewController method. This is the method where we will get our data from SecondViewController. Inside this function we will update the Label with the received data. To update the label we do:

self.receivedDataLabel.text = myData

But Wait !!

Our job is not complete. There is one very important thing which we haven’t done yet. While we are transitioning from FirstViewController to SecondViewController we need to set-up our delegate. For this we will override the prepare-for-segue method. This method is called just before we actually transition to a new view controller. Inside this method we will set SecondViewController as the destination view controller and set-up the Delegate to self (remember delegate was initialized with nil in SecondViewController). By setting it to self we tell that this class is itself acting as the delegate.

Once everything is set-up our FirstViewController.swift file should look like this:

Conclusion

Our iOS app is finally completed and is ready to be run. Using delegates and protocols keeps the overall process simple yet efficient.

You can download the complete project here.

I hope you found this article helpful. If you did, please share this post with your friends or colleagues who might find it useful.

--

--