Aman Chawla
Aman Chawla

Reputation: 229

Pass data between ViewControllers using dismiss

I have 3 ViewControllers A B C. A and B ViewControllers use C to get data. Both A and B have a select button so if user is on A ViewController and presses select a segue is performed to C the user selects data that is stored in a dictionary pressed done and segue is performed to come back to A and dictionary is sent back using prepare for segue. Exactly the same if user is on B ViewController.

Problems How do I let C know which ViewController to send the dictionary back to. Is their a way I can use dismiss to send the dictionary back to the ViewController the user came from or maybe a better way.

Code from C ViewContrller

@IBAction func doneBtnPressed(_ sender: Any) {
    performSegue(withIdentifier: "backToAddMeetingVC", sender: self)

    //Cant work cuz cant perform 2 segues at once
    performSegue(withIdentifier: "backToProjectVC", sender: <#T##Any?#>)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "backToAddMeetingVC" {
        let destination = segue.destination as! AddMeetingVC
        destination.selectedMembers = self.selectedMembers
    }

    if segue.identifier == "backToProjectVC" {
        let destination = segue.destination as! ProjectsVC
        destination.selectedMembers = self.selectedMembers

    }
}

Upvotes: 0

Views: 546

Answers (3)

Sergei Navka
Sergei Navka

Reputation: 104

In C controller create

var dismissClosure: ((neededData) -> Void)?

In controller which presented C its controller(B) in prepareSegue need to declare this:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let controller = segue.destination as! C
    controller.dismissClosure = { [weak self] neededData in
        guard let `self` = self else { return }
        //TODO YOUR CHANGES
    }
}

When you dismiss or pop controller call this block in C controller

dismiss:

dismiss(true) {
   dismissClosure?(neededData)
}

pop

dismissClosure?(neededData)
navigationController?.popViewController(animated: true)

Upvotes: 2

Rajeev Singh
Rajeev Singh

Reputation: 198

You can use a global variable name like mySelectedViewController and sets its value whenever button action is performed, like when you click from ViewController A set mySelectedViewController = viewA and then in C ViewController check mySelectedViewController value and work according to it.

Upvotes: 0

Kamran
Kamran

Reputation: 15258

Inside doneBtnPressedeither use below if you are not using navigationController

self.dismiss(animated: true, completion: nil)

OR

use below line if you are using navigationController

self.navigationController?.popViewController(animated: true)

prepare for segue looks fine

Upvotes: 0

Related Questions