Search code examples
swift2uialertviewuialertcontrollerlocalnotification

Swift: Show UIAlertController in didReceiveLocalNotification method


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)

Solution

  • 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.