Swift:在didReceiveLocalNotification方法中显示UIAlertController

时间:2016-02-27 07:25:12

标签: swift2 uialertview uialertcontroller localnotification

我希望在应用程序运行时触发通知时显示警报,这里是我用于本地通知的tutorial。在教程中,它使用UIAlertView来显示警报并且它可以工作,这里是代码:

func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
    // Point for handling the local notification when the app is open.
    // Showing reminder details in an alertview
    UIAlertView(title: notification.alertTitle, message: notification.alertBody, delegate: nil, cancelButtonTitle: "OK").show()
}

但是它警告UIAlertView在iOS 9中已被弃用,所以我使用了UIAlertController,但是当我运行它时会发出警告:

Attempt to present <UIAlertController: 0x7c322a00> on <xxx> whose view is not in the window hierarchy!

这是我的didReceiveLocalNotification方法:

func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
    let alert = UIAlertController(title: "", message: notification.alertBody, preferredStyle: UIAlertControllerStyle.Alert)
    alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: {(action: UIAlertAction!) in
    }))

    self.window?.rootViewController?.presentViewController(alert, animated: true, completion: nil)
}

如何在didReceiveLocalNotification方法中显示UIAlertController?我也尝试过:

 let activeViewCont = application.windows[0].rootViewController?.presentedViewController
 activeViewCont!.presentViewController(alert, animated: true, completion: nil)

1 个答案:

答案 0 :(得分:9)

试试这个:

func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {

    var topController : UIViewController = (application.keyWindow?.rootViewController)!

    while ((topController.presentedViewController) != nil) {

        topController = topController.presentedViewController!
    }

    let alert = UIAlertController(title: "", message: notification.alertBody, preferredStyle: UIAlertControllerStyle.Alert)
    alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: {(action: UIAlertAction!) in}))

    topController.presentViewController(alert, animated: true, completion: nil)

})

希望它有所帮助。

相关问题