dismiss UIAlertController presented by a modal view controller

16,046

Don't call self dismissViewController in the button handler. That specifically states that you want the view controller dismissed.

You don't need to dismiss the alert. It will automatically dismiss itself. The only thing you should do in the button handler is perform whatever action you need. Do nothing if you don't need to do anything.

If your alert is simply a message and you don't need to perform any action, just do this:

UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
Share:
16,046
Sunnyside Productions
Author by

Sunnyside Productions

Started ios programming October 2014. Hope to be useful to the community someday, but for now I'll just be asking questions I suppose.

Updated on June 06, 2022

Comments

  • Sunnyside Productions
    Sunnyside Productions about 2 years

    I seem to be running into a problem similar to one in an unresolved posted question: UIAlertController dismissing his presentingViewController

    I am presenting a modal view controller on top of a normal UIViewController. Then I'm popping up an alert on that modal view controller. When I push "ok" to dismiss the alert (generated with the code below), the modal view controller is also dismissed.

    UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK"
                                                 style:UIAlertActionStyleDefault 
                                               handler:^(UIAlertAction *action{ 
                                                        [self dismissViewControllerAnimated: YES completion: nil];}];
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Sign up problem."
                                                                   message:@"Some fields are empty. Please check your inputs and try again."
                                                            preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:ok];
    [self presentViewController:alert animated:YES completion:nil];
    

    How can I dismiss just the alert?

    I realize I can avoid this problem by using a navigation controller type setup instead and hiding the navigation bar, so I Get the same feel as the modal view controller, but this seems silly. Thanks.