Search code examples
iosswiftuialertcontrollerrootviewcontroller

Dismissing a View Controller, then presenting an Alert Controller


In my project, I am using rootViewController?.dismiss to dismiss some View Controllers back to the main VC.

In the completion handler, I would like to present a UIAlertController on the main View Controller once it becomes visible again.

My problem is the UIAlertController never appears. My hunch is because I'm using self in the launchFrom parameter. Do I need to get a reference back to the main VC, and present it there?

Dismiss VC and try presenting Alert:

self.view.window!.rootViewController?.dismiss(animated: false, completion: {
    Constants.presentThankYou(launchFrom: self)
})

presentThankYou method

static func presentThankYou(launchFrom: UIViewController) {
    let alertController = UIAlertController(title: "Thank You!", message: "You did it!", preferredStyle: UIAlertControllerStyle.alert)
    let okAction = UIAlertAction(title: "Close", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in
        print("Done")
    }
    alertController.addAction(okAction)
    launchFrom.present(alertController, animated: true, completion: nil)
}

How do I present the Alert Controller after all of my VC's have been dismissed?


Solution

  • Out of my head, Try doing it in viewDidAppear. To prevent the alert from showing up all the time, use a bool shouldShowThankYouAlert and set this value to true in the dismiss completion handler