Search code examples
iosswiftuinavigationcontrollersegueviewwilldisappear

How to pass data to parent view controller


I'm performing a segue on my parent VC when clicked on an image. I want to pass data back to the parent VC from child VC. I've been exploring various options to pass data back to parent VC but can't figure it out.

Since the child VC is part of Navigation and it's presented (show) via segue there should be an easy way to pass data back to parent.

How to do it?

I've tried viewWillDisappear method but parentVC is nil in following code.

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    if self.isMovingFromParent {
        if let navVC = self.presentingViewController as? UINavigationController {
            if let parentVC = navVC.viewControllers.first as? ParentViewController {
                print("viewWillDisappear() moving to parent") // Not executed
                parentVC.data = self.data
            }
        }
    }
}

Solution

  • One strategy would be to set the parent as a delegate of the child. You would create this relationship in a prepare(for:sender:) function.

    If you are unfamiliar with delegation, this article is a good guide: https://medium.com/@jamesrochabrun/implementing-delegates-in-swift-step-by-step-d3211cbac3ef