iosswiftuiwindowuialertcontroller

Dismiss all UIAlertControllers currently presented


Is there a way to dismiss all UIAlertControllers that are currently presented?

This is specifically because from anywhere and any state of my app, I need to get to a certain ViewController when a push notification is pressed.


Solution

  • You could subclass your UIAlertControllers, attach NSNotification observers to each which would trigger a method within the UIAlertController subclass to dismiss the alert controller, then post an NSNotification whenever you're ready to dismiss, ex:

    class ViewController: UIViewController {
        func presentAlert() {
            // Create alert using AlertController subclass
            let alert = AlertController(title: nil, message: "Message.", preferredStyle: UIAlertControllerStyle.Alert)
            // Add observer to the alert
            NSNotificationCenter.defaultCenter().addObserver(alert, selector: Selector("hideAlertController"), name: "DismissAllAlertsNotification", object: nil)
            // Present the alert
            self.presentViewController(alert, animated: true, completion:nil)
        }
    }
    
    // AlertController subclass with method to dismiss alert controller
    class AlertController: UIAlertController {
        func hideAlertController() {
            self.dismissViewControllerAnimated(true, completion: nil)
        }
    }
    

    Then post the notification whenever you're ready to dismiss the alert (in this case, when the push notification is pressed):

    NSNotificationCenter.defaultCenter().postNotificationName("DismissAllAlertsNotification", object: nil)