Passing Data Between View Controllers in Swift

Passing data from one view controller to another view controller is something you need in almost every app. But yet I have seen many people struggling in this. So I have decided to write this blog for beginner level iOS App Developers to understand how to pass the data.

There could be two scenarios when you are changing the view controllers.

  1. You are moving from ViewController1 to ViewController2
  2. You are coming back from ViewController2 to ViewController1

Also, there could be two ways in which you are moving from ViewController1 to ViewController2.

  1. Using the navigation controller
  2. Using storyboard segues.

Now, we will discuss passing data between the view controllers using the navigation controller and using storyboard segues separately.

Passing data when pushing or presenting View Controller

1. Sending data from ViewController1 to ViewController2

For navigating from VC1 to VC2, we use the “push” method. For coming back from VC2 to VC1, we use the “pop” method. We can also use “present” if we want to present our view controller modally.

Below is the code to move from VC1 to VC2

//1 Instantiating ViewController2 from storyboard
let vc2 = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "ViewController2") as! ViewController2

//2 pushing ViewController2 to move to top of the navigation stack
self.navigationController?.pushViewController(vc2, animated: true) 

The above code would take you from VC1 to VC2. But where are we passing data? Relax.

//1  
let vc2 = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "ViewController2") as! ViewController

//2
vc2.myName = self.userName
        
//3
self.navigationController?.pushViewController(vc2, animated: true)

So in the above code, you can see #2, here we are assigning self.userName, which is in ViewController1 to vc2.myName. When the View Controller 2 will load, its myName value will be equal to the value of self.userName that we passed.

Easy, Right? similarly, you may also do when presenting your view controller modally.

//1  
let vc2 = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "ViewController2") as! ViewController

//2
vc2.myName = self.userName
        
//3
self.present(vc2, animated: true, completion: nil)

You can pass any data type, whether string, array, JSON, etc.

Sending data back from ViewController2 to ViewController1

Sending data forward is easy. While sending data back to the controller can be a bit tricky for beginners.

Data is sent back to the controller with the help of Delegates.

Delegates are a design pattern that allows one object to send messages to another object when a specific event happens.

James Rochabrun

I am writing a separate blog on sending data back to View Controller using Delegates. I will update the link here.

Passing Data using Segues

Segues are another way of transition from one view controller to others and are implemented through a storyboard. I will not cover how to create a segue here as I assume you already know it. If not, here is the link from Apple Documentation

The starting point of a segue must be a view or object with a defined action, such as a control, bar button item, or gesture recognizer. You can also create segues from cell-based views such as tables and collection views.

Apple Docs

Segues can be implemented in two ways:

  1. From a view or object to Next View Controller
  2. From View Controller to Next View Controller

When you do not need to pass any data, you can create an object to Next View Controller segue and implemented it all through a storyboard.

But when you need to pass the data, we need to make sure to create the segue between View Controller to View Controller. There can be multiple segues between view controllers and we use segue identifiers to identify them.

Go ahead and create a segue from ViewController1 to ViewController2 and click on the connecting arrow line to open it in Attribute Inspector in the right panel. Here, assign the identifier to the segue. For example: “nextVCSegue”

Also, create a button in your ViewController1 on click of which we will perform the segue. Declare an @IBAction of that button.

//1 
 @IBAction func submitBtnPressed(_ sender : Any) {
    //2
    performSegue(withIdentifier: "nextVCSegue", sender: self)
 }
  
 //3 prepareForSegue function is called everytime you perform a segue.

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        //4
        if segue.identifier == "nextVCSegue" {
            //5
            if let nextVC = segue.destination as? ViewController2 {
                //6
                nextVC.myName = self.name
            } else {
                print("error")
            }
        }
    }
  1. We created an @IBAction that will execute on the submit button click.
  2. Here we are telling the controller to perform segue using the identifier “nextVCSegue”.
  3. Now when performSegue starts, it will call prepareForSegue function. In this function, we will assign the data that we need to pass to the next view controller.
  4. PrepareForSegue function is called for every segue that is happening from the view controller. But here in our case, we only want to pass the data when the segue is from ViewController1 to ViewController2. And how would we identify it? Yes. Using segue Identifier. So we will check if the segue identifier is “nextVCSegue” or not.
  5. segue has a destination property that you can use to know what your destination view controller is. So here we are assigning out nextVC object to the destination view controller which is ViewController2.
  6. Now we can use nextVC to access all the properties you declared in ViewController2 and assign its value here. So here we are assigning our name variable value to nextVC myName variable.

Done. You have successfully passed your data from ViewController1 to ViewController2.

Subscribe below to receive latest blog updates directly in your inbox and help yourself become a better developer.

1 Comment

Leave a Comment