Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple UIAlertControllers in iOS

In my app there are scenarios where multiple alerts could come. But as in iOS8 UIAlertview turned to UIAlertController, i am not able to show multiple alerts as you can not present two or more controllers at the same time.

How can I achieve this using UIAlertController?

like image 736
knowledgeseeker Avatar asked Jul 14 '15 15:07

knowledgeseeker


2 Answers

You need to present it on a top presented controller, you can use this extension:

extension UIViewController {

    var topController: UIViewController {
        presentedViewController?.topController ?? self
    }
}
self.topController.present(alert, animated: true)
like image 137
Artem Sydorenko Avatar answered Sep 28 '22 02:09

Artem Sydorenko


You can keep track of a list of alerts to show in your view controller as an instance variable, say

NSMutableArray *alertsToShow;

You can present the first UIAlertController, and add a UIAlertAction in which you present the next alert (if applicable), with a recursive-like method:

- (void)showAlertIfNecessary {
    if (alertsToShow.count == 0)
        return;

    NSString *alert = alertsToShow[0];
    [alertsToShow removeObjectAtIndex:0];

    UIAlertController *alertController = [UIAlertController
                          alertControllerWithTitle:@"Title"
                          message:alert
                          preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction 
        actionWithTitle:@"OK"
                  style:UIAlertActionStyleDefault
                handler:^(UIAlertAction *action)
                {
                    [self showAlertIfNecessary];
                }];
    [alertController addAction:okAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

Note that this can get very annoying to the user, if he/she needs to click through a lot of messages. You might consider combining them into a single message.

like image 33
Glorfindel Avatar answered Sep 28 '22 04:09

Glorfindel