Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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)