Display Alert Message from viewDidLoad

Shivani Arorra picture Shivani Arorra · Jan 9, 2016 · Viewed 9.8k times · Source

I want to display a alert message from viewDidLoad() method of ViewController.m instead from viewDidAppear() method.

Here is my code :

- (void)viewDidLoad {
    [super viewDidLoad];

    //A SIMPLE ALERT DIALOG
    UIAlertController *alert =   [UIAlertController
                              alertControllerWithTitle:@"My Title"
                              message:@"Enter User Credentials"
                              preferredStyle:UIAlertControllerStyleAlert];


    UIAlertAction *cancelAction = [UIAlertAction
                               actionWithTitle:NSLocalizedString(@"Cancel", @"Cancel action")
                               style:UIAlertActionStyleCancel
                               handler:^(UIAlertAction *action)
                               {
                                   NSLog(@"Cancel action");
                               }];

    UIAlertAction *okAction = [UIAlertAction
                           actionWithTitle:NSLocalizedString(@"OK", @"OK action")
                           style:UIAlertActionStyleDefault
                           handler:^(UIAlertAction *action)
                           {
                               NSLog(@"OK action");
                           }];

    [alert addAction:cancelAction];
    [alert addAction:okAction];
    [self presentViewController:alert animated:YES completion:nil];
}

and I am getting this error:

Warning: Attempt to present <UIAlertController: 0x7fbc58448960> on <ViewController: 0x7fbc585a09d0> whose view is not in the window hierarchy!

Answer

Woodstock picture Woodstock · Jan 9, 2016

OK not a bug, the issue is that in viewDidLoad the view hierarchy is not fully set. If you use viewDidAppear, then the hierarchy is set.

If you really want to call this alert in viewDidLoad you can do so by wrapping your presentation call in this GCD block to cause a slight delay, waiting for the next run loop, however I suggest you don't (it's ugly).

dispatch_async(dispatch_get_main_queue(), ^ {
    [self presentViewController:alert animated:YES completion:nil];
});