Swift: Show UIAlertController in didReceiveLocalNotification method

不羁的心 提交于 2019-12-11 09:58:35

问题


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

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!

Here is my didReceiveLocalNotification method:

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

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)

回答1:


Try this:

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)

})

Hope it helps.



来源:https://stackoverflow.com/questions/35666983/swift-show-uialertcontroller-in-didreceivelocalnotification-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!