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!
Adding Action Buttons to Alert Dialog To create an action button that the user can tap on, we will need to create a new instance of an UIAlertAction class and add it to our alert object. To add one more button to UIAlertController simply create a new UIAlertAction object and add it to the alert.
-viewDidLoad will be called once whenever the view controller needs to load its view hierarchy. Obviously, that'll happen the first time that the controller accesses its view. If the view controller later unloads its view, then -viewDidLoad will be called again the next time the view is loaded.
viewWillAppear(_:) Always called after viewDidLoad (for obvious reasons, if you think about it), and just before the view appears on the screen to the user, viewWillAppear is called.
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];
});
to move this call to the viewDidAppear: method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With