0

I'm trying to pass data from a SecondViewController to my FirstViewController when I click on my back button (UINaviagtionController).

For pass my data from FirstViewController to the SecondViewController I do this:

if segue.identifier == "showSecondVC" {
  let vc = segue.destination as! SecondViewController
  vc.rows = rows[pathForAVC]
  vc.lap = lapTime[pathForAVC]
  vc.indexPath = pathForAVC
}

But I have no idea how to pass data from SecondViewController to the FirstViewController and I really don't understand topics about it on Stack Overflow.

I want to transfer it when I click here:

Back button from a NavigationBar

Thanks.

pierreafranck
  • 435
  • 5
  • 18

2 Answers2

1

You should have a custom protocol such as:

public protocol SendDataDelegate: class {
    func sendData(_ dataArray:[String])
}

Here I suppose you want to send a single array back to FirstViewController

Then make your first view controller to conform to the custom protocol, such as:

class FirstViewController: UIViewController, SendDataDelegate  

In the second view controller, create a delegate a variable for that protocol, such as:

 weak var delegate: SendDataDelegate?

and then you catch the back action and inside it you call your custom protocol function, such as:

self.delegate?.sendData(arrayToSend)

In the first viewController, in the prepare for segue function just set the delegate like

vc.delegate = self
Aravind A R
  • 2,576
  • 1
  • 10
  • 23
1

You can use delegate pattern for that. You can grab the back button press event like this and update the data

   override func viewWillDisappear(_ animated: Bool) {
    if self.isMovingFromParentViewController {
        self.delegate.updateData( data)
    }
    }

For more information on delegates you can go through this.

Actually things depend on your requirement, if you want data to be updated in first view controller as soon as it is updated in second view controller, you would need to call delegate as soon as the data is updated. But as in the question you have mentioned that you want it to be updated on back button only, above is the place to do it.

Another way would be to have Datasource as singleton so that it is available to all the view controllers and the changes are reflected in all view controllers. But create singleton if absolutely necessary, because these nasty guys hang around for entire time your application is running.

Mohammad Sadiq
  • 4,041
  • 25
  • 25