eLocalNotification方法中显示UIAlertCo

eLocalNotification方法中显示UIAlertCo

本文介绍了Swift:在didReceiveLocalNotification方法中显示UIAlertController的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在应用运行时触发通知时显示警报,这是教程.在教程中,它使用UIAlertView来显示警报,并且可以正常工作,这里是代码:

I want to show alert when notification is fired while app is running, here is tutorial which i used for local notifications. In tutorial, it uses UIAlertView to show alert and it works, here is code:

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()
}

但是它警告说iOS 9中不推荐使用UIAlertView,所以我使用了UIAlertController,但是当我运行它时,它给出了警告:

but it gives warning that UIAlertView is deprecated in iOS 9, so i used UIAlertController, but when i run it it gives warning:

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?我也尝试过:

How i can show UIAlertController in didReceiveLocalNotification method? I also tried:

 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)

})

希望有帮助.

这篇关于Swift:在didReceiveLocalNotification方法中显示UIAlertController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 06:18