Swift:在didReceiveLocalNotification方法中显示UIAlertController

kak*_*jan 1 uialertview localnotification uialertcontroller swift2

我想在应用程序运行时触发通知时显示警报,这是我用于本地通知的教程.在教程中,它用于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()
}
Run Code Online (Sandbox Code Playgroud)

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

Attempt to present <UIAlertController: 0x7c322a00> on <xxx> whose view is not in the window hierarchy!
Run Code Online (Sandbox Code Playgroud)

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

我怎么能在didReceiveLocalNotification方法中显示UIAlertController ?我也尝试过:

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

Nis*_*ant 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)

})
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你.