取消当前显示的所有UIAlertControllers

Dav*_*vid 3 uiwindow ios swift uialertcontroller

有没有办法消除当前提供的所有UIAlertControllers?

这特别是因为在我的应用程序的任何位置和任何状态下,当按下推送通知时,我都需要进入某个ViewController。

Aga*_*jan 5

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

这对我有用!


Lyn*_*ott 4

您可以对您的UIAlertControllers 进行子类化,将NSNotification观察者附加到每个观察者,这将触发子类中的方法UIAlertController来关闭警报控制器,然后NSNotification在您准备好关闭时发布一个,例如:

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,每当您准备好消除警报时(在本例中,当按下推送通知时),就发布通知:

NSNotificationCenter.defaultCenter().postNotificationName("DismissAllAlertsNotification", object: nil)
Run Code Online (Sandbox Code Playgroud)