iOS

jean-marie castellucci
jean-marie castellucci
4,954 Points

Present UIAlertView from appDelegate

I m trying to display a UIAlertView from the appDelegate in didReceiveRemoteNotification when the app receive a push notification.

I ve this error :

       Warning: Attempt to present <UIAlertController: 0x14c5494c0> on   <UINavigationController:
       0x14c60ce00> whose view is not in the window hierarchy!

here is my code :

           func application(application: UIApplication,     didReceiveRemoteNotification userInfo: NSDictionary) {

           var contentPush: NSDictionary = userInfo.objectForKey("aps") as NSDictionary

           var message = contentPush.objectForKey("alert") as String



           let alertController = UIAlertController(title: "Default Style", message: message, preferredStyle: .Alert)

           let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in
                    // ...
    }
           alertController.addAction(cancelAction)

           let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in

            let photoPushedVc = self.storyboard.instantiateViewControllerWithIdentifier("CommentTableViewController") as CommentTableViewController

            println("the fetched post is \(post)")

            photoPushedVc.post = post

            let activeVc = UIApplication.sharedApplication().keyWindow?.rootViewController

            activeVc?.presentViewController(photoPushedVc, animated: true, completion: nil)
   }

            alertController.addAction(OKAction)

            let activeVc = UIApplication.sharedApplication().keyWindow?.rootViewController


            activeVc?.presentViewController(alertController, animated: true, completion: nil)

1 Answer

jean-marie castellucci
jean-marie castellucci
4,954 Points

ok i finaly got it :

you need to get the active VC using this :

                let navigationController = application.windows[0].rootViewController as UINavigationController

                let activeViewCont = navigationController.visibleViewController

                activeViewCont.presentViewController(alertController, animated: true, completion: nil)