Present UIAlertController from AppDelegate

28,410

Solution 1

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

Solution 2

try this code..

-(void)application:(UIApplication *)application               didReceiveLocalNotification:(UILocalNotification *)notification
{
 NSLog(@"rakshapettu");
 UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"AlertView" message:@"I am an AlertView" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                      handler:^(UIAlertAction * action) {
                                                          [alert dismissViewControllerAnimated:YES completion:nil];
                                                      }];
[alert addAction:defaultAction];
UIWindow *alertWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
alertWindow.rootViewController = [[UIViewController alloc] init];
alertWindow.windowLevel = UIWindowLevelAlert + 1;
[alertWindow makeKeyAndVisible];
[alertWindow.rootViewController presentViewController:alert animated:YES completion:nil]; 
}

Solution 3

It's better to use something like:

var hostVC = self.window?.rootViewController

while let next = hostVC?.presentedViewController {
    hostVC = next
}

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

Previous answers won't work if you are already presenting modal view controller.

Solution 4

you call it before the window is up and the navigationController is actually shown:

"Warning: Attempt to present on whose view is not in the window hierarchy!"

likely you do so in applicationDidFinishLaunching?


EITHER wait .. like do it when the view really appears

OR

one 'hack' would be to force the view and window up yourself:

[self.window addSubview:self.rootViewController.view];
[self.window makeKeyAndVisible];

Solution 5

I was trying the same but does not work because after change of viewcontroller still returned the initial viewcontroller and throw the error whose view is not in the window hierarchy!. Finally, I found the solution to this problem:

UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)

But I have to force view controllers to update de keyWindow with this:

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    UIApplication.sharedApplication().keyWindow!.rootViewController = self
    UIApplication.sharedApplication().keyWindow!.makeKeyAndVisible()
}
Share:
28,410
Satre
Author by

Satre

Creative Coder, Graphics Engineer, Artist, and Dancer studying at University of California, San Diego

Updated on June 12, 2020

Comments

  • Satre
    Satre about 4 years

    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?

  • Zeb
    Zeb almost 9 years
    Hi @AdiQuadCore, your is useful only in swift application. In objC, the UIAlertController needs a pointer to the current UIViewController.
  • Seoras
    Seoras over 7 years
    This worked for me in ObjC in didFinishLaunchingWithOptions
  • NerdyTherapist
    NerdyTherapist over 7 years
    Perfect answer and a really good method to handle modally presented view controllers! Thanks!
  • Colin Basnett
    Colin Basnett over 7 years
    UIAlertView is now deprecated.
  • mfaani
    mfaani over 7 years
    If you aren't not creating a new Window, do you still have to do makeKeyAndVisible? For window that comes with AppDelegate, doesn't that happen by default?!
  • Daij-Djan
    Daij-Djan over 7 years
    In General: yes BUT It happens too late for the op's question
  • mfaani
    mfaani over 7 years
    I'm confused. what do you mean too late? Is your code correct or not?
  • Daij-Djan
    Daij-Djan over 7 years
    Mine is correct for the given question :) makeKeyAndVisible is needed here
  • Rafael Nobre
    Rafael Nobre over 7 years
    You should not do that, really.
  • meaning-matters
    meaning-matters almost 6 years
    How is the UIWindow deallocated?