简体   繁体   中英

Using UIAlertController in Xcode 8 with Objective-C

I am trying to show a UIAlertController every time the user start the app.

- (void)viewDidLoad {
    [super viewDidLoad];

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"My alert" message:@"This should be come when the app start" preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *yesButton = [UIAlertAction actionWithTitle:@"YES" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }];

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

But this is not working. I run the app in Xcode simulator. The app runs but no alertview is showing. What am I doing wrong?

Try opening the UIAlertController in the viewDidAppear: delegate instead. Alternatively, you could show it as part of your AppDelegate method didFinishLaunchingWithOptions: to make it more view-controller independent.

As you are newbie in iOS so you must spend your little time to understand all the functions of appdelegate class and after that viewController life cycle method so you will know about the startup behavior of application this will solve your problem like you shared above :)

App delegate methods:

  • application:didFinishLaunchingWithOptions: —This method allows you to perform any final initialization before your app is displayed to the user.

  • application:willFinishLaunchingWithOptions: —This method is your app's first chance to execute code at launch time.

  • applicationDidBecomeActive: —Lets your app know that it is about to become the foreground app. Use this method for any last minute preparation.

  • applicationWillResignActive: —Lets you know that your app is transitioning away from being the foreground app. Use this method to put your app into a quiescent state.

  • applicationDidEnterBackground: —Lets you know that your app is now running in the background and may be suspended at any time.

  • applicationWillEnterForeground: —Lets you know that your app is moving out of the background and back into the foreground, but that it is not yet active.

  • applicationWillTerminate: —Lets you know that your app is being terminated. This method is not called if your app is suspended.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM