Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show UIAlertController if already showing an Alert

Difference between the legacy UIAlertView and the new UIAlertController is that the latter needs to be presented onto a specific viewcontroller with presentViewController:animated:completion:. This poses an awkward problem for my use case: what if there is already an UIAlertController showing (e.g. a rating dialog) when a second viewcontroller gets presented (e.g. an error dialog due to failed network connection). I have experienced that in this case the second UIAlertController just does not show.

Edit: At the moment I try to show an alert, I do not know if there currently is anything presenting.

How do you cope with this situation?

like image 239
fabb Avatar asked Oct 17 '14 06:10

fabb


2 Answers

I found a workaround to find out which viewcontroller I can present the alert upon. I also posted the answer here:

@implementation UIViewController (visibleViewController)

- (UIViewController *)my_visibleViewController {

    if ([self isKindOfClass:[UINavigationController class]]) {
        // do not use method visibleViewController as the presentedViewController could beingDismissed
        return [[(UINavigationController *)self topViewController] my_visibleViewController];
    }

    if ([self isKindOfClass:[UITabBarController class]]) {
        return [[(UITabBarController *)self selectedViewController] my_visibleViewController];
    }

    if (self.presentedViewController == nil || self.presentedViewController.isBeingDismissed) {
        return self;
    }

    return [self.presentedViewController my_visibleViewController];
}

@end

// To show a UIAlertController, present on the following viewcontroller:
UIViewController *visibleViewController = [[UIApplication sharedApplication].delegate.window.rootViewController my_visibleViewController];
like image 110
fabb Avatar answered Oct 21 '22 14:10

fabb


Since UIAlertController is itself a UIViewController, you can present a second UIAlertController on top of the first one by presenting from the existing one:

alertController.PresentViewController(alertController2,  animated: true, completionHandler: null)
like image 5
Bbx Avatar answered Oct 21 '22 14:10

Bbx