Present UIAlertController from AppDelegate

Satre picture Satre · Nov 16, 2014 · Viewed 27.7k times · Source

I'm trying to present a UIAlertController from the AppDelegate in my iOS app. Below is the alert and the present method.

UIAlertController *alert = [UIAlertController alertControllerWithTitle:cTitle message:cMessage preferredStyle:UIAlertControllerStyleAlert];

//Configure alert and actions

[self.window.rootViewController presentViewController:alert animated:TRUE completion:nil];

However, when I try to present the alert, it doesn't appear and I get the following alert in the console.

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

What is causing the error and how do I fix it?

Answer

Aditya Gaonkar picture Aditya Gaonkar · Jul 23, 2015

You can use this code as well if you want to launch it from didFinishLaunchingWithOptions.Hope this helps.

dispatch_async(dispatch_get_main_queue(), {
              let importantAlert: UIAlertController = UIAlertController(title: "Action Sheet", message: "Hello I was presented from appdelegate ;)", preferredStyle: .ActionSheet)
            self.window?.rootViewController?.presentViewController(importantAlert, animated: true, completion: nil)
        })

And up-to-date:

DispatchQueue.main.async {
    let alert = UIAlertController(title: "Hello!", message: "Greetings from AppDelegate.", preferredStyle: .alert)
    self.window?.rootViewController?.present(alert, animated: true, completion: nil)
}