Swift: 在 didReceiveLocalNotification 方法中显示 UIAlertController

Swift: Show UIAlertController in didReceiveLocalNotification method

我想在应用 运行ning 时触发通知时显示警报,这是我用于本地通知的 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)

试试这个:

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)

})

希望对您有所帮助。