iOS get notified in parent viewcontroller when presented viewcontroller is dimissed

1.1k Views Asked by At

I have a view controller which presents another view controller and within the presented viewcontroller , user makes choices which will lead to many other notifications to be pushed but when we dismiss the presentation viewcontroller I would like original parent viewcontroller to be notified as viewwillappear is not firing.

2

There are 2 best solutions below

4
On

You may post the notification from child when it's about to be dismissed and observe the notification in parent view controller.

In parent view controller

NotificationCenter.default.addObserver(self, selector: #selector(methodtobecalled(_:)), name: "childdismissed", object: nil)

 @objc func methodtobecalled(_: Notification) {
        
    }

In child viewcontroller when you choose to dismiss , send the notification

NotificationCenter.default.post(name: "childdismissed", object: nil, userInfo: nil)

Adopt the class UIAdaptivePresentationControllerDelegate in presented view controller

add below delegate methods

func presentationControllerShouldDismiss(_ presentationController: UIPresentationController) -> Bool {
        return false
    }

func presentationControllerDidAttemptToDismiss(_ presentationController: UIPresentationController) {
    dismiss(animated: true, completion: nil)
   // Post the notification here

}

3
On

You can add a block handler to your child controller to notify the parent controller with the user choice:

struct Choice {
  // whatever object that represents the user choice
}

class ChildController: UIViewController {

  var completionHandler: ((ChildController, Choice) -> Void)?

  func finishPresentation(with choice: Choice) {
     // Suppose this function is called when user picks something in the user interface
     completionHandler?(self, choice)
  }

}

Then in parent controller, assign the completionHandler to get notified with the user choice.

class ParentController: UIViewController {
  func presentChild() {
     let controller = ChildController()

     controller.completionHandler = { child, choice
        child.dismiss(animated: true) {
          // do something with the user choice
        }
     }

     present(controller, animated: true)
  }
}