Search code examples
iosswift5

ios - how to know if second controller is dismissed?


is it possible to handle and trigger some func in first controller if second controller is dimissed?

this my code to open second controller from first controller

self.present(UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "LockScreen") as UIViewController, animated: true, completion: nil)

and this my code to dismiss controller from second controller to first controller

self.navigationController?.popViewController(animated: true)

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

Solution

  • Inside your LockScreen controller, declare a closure to handle when dismissed:

    class LockScreen: UIViewController {
        var onDismissHandler: (() -> ())?
        
        func dismissController() {
            self.dismiss(animated: true, completion: onDismissHandler)
        }
    }
    

    Then when you're presenting LockScreen:

    func onPresent() {
        let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(identifier: "LockScreen") as LockScreen
        controller.onDismissHandler = { [weak self] in
            // TODO: Do something when dismissed
        }
        self.present(controller, animated: true, completion: nil)
    }