Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 344
David Avatar asked Feb 20 '15 19:02

David


2 Answers

func dismissAnyAlertControllerIfPresent() {
    guard let window :UIWindow = UIApplication.shared.keyWindow , var topVC = window.rootViewController?.presentedViewController else {return}
    while topVC.presentedViewController != nil  {
        topVC = topVC.presentedViewController!
    }
    if topVC.isKind(of: UIAlertController.self) {
        topVC.dismiss(animated: false, completion: nil)
    }
}

This worked for me!

like image 137
Agam Mahajan Avatar answered Sep 19 '22 21:09

Agam Mahajan


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)
like image 33
Lyndsey Scott Avatar answered Sep 19 '22 21:09

Lyndsey Scott