Search code examples
iosobjective-cuialertviewcontroller

iOS/Objective-C: Call AlertViewController from sharedInstance


I am updating some UIAlertViews, deprecated since iOS 9.0 to UIAlertViewControllers.

With UIAlertView, it was possible to just throw an alert from any code being executed--even in a utility class or shared instance--with the simple line:

[alertView show];

So if I call a shared instance such as

- (void)didTapDeleteButton:(id)sender {
    NSArray *itemsToDelete = [self.selectedIndexPathToContact allValues];

    [[IDModel sharedInstance] deleteItems:itemsToDelete];

//which contains the code:

UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Keep Archive Copy?"
                                                    message:nil
                                                   delegate:self
                                          cancelButtonTitle:@"No"
                                          otherButtonTitles:@"OK",nil];
alertInvite.alertViewStyle = UIAlertViewStyleDefault;
alertInvite.tag=100;
[alertView show];

everything worked fine.

However, with the UIAlertController, this is not allowed. If you put the following code in the method of a class accessible via shared instance, when you get to presentViewController, it throws an error:

UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"Delete Item?" message:nil preferredStyle:UIAlertControllerStyleAlert];

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

UIAlertAction* noButton = [UIAlertAction actionWithTitle:@"Not Now" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
    [alertView dismissViewControllerAnimated:YES completion:nil];
}];

[alertView addAction:noButton];
[alertView addAction:yesButton];
if ([alertView respondsToSelector:@selector(setPreferredAction:)]) {
    [alertView setPreferredAction:yesButton];
}
//FOLLOWING THROWS ERROR
[self presentViewController:alertView animated:YES completion:nil];

on the last line, that the class (reached via a shared instance) does not have this method. It seems you must use a more complicated way to throw alert. I've seen some somwehat convoluted approaches such as the following:

id rootViewController = [UIApplication sharedApplication].delegate.window.rootViewController;
if([rootViewController isKindOfClass:[UINavigationController class]])
{
    rootViewController = ((UINavigationController *)rootViewController).viewControllers.firstObject;
}
if([rootViewController isKindOfClass:[UITabBarController class]])
{
    rootViewController = ((UITabBarController *)rootViewController).selectedViewController;
}
[rootViewController presentViewController:alertInvite animated:YES completion:nil];

However, this does not work for me as I don't think my shared instance has a rootviewcontroller. Can anyone suggest a simple, straightforward way to do this?


Solution

  • I created an extension on UIViewController that allows me to create a new window and present a view controller from there. This allows me to present from any class, not just a view controller. Also, it prevents issues where you try to display an alert view from a view controller that is already presenting a view controller.

    extension UIViewController {
        func presentFromNewWindow(animated: Bool = true, completion: (() -> Void)? = nil) {
            let window = newWindow()
    
            if let rootViewController = window.rootViewController {
                window.makeKeyAndVisible()
                rootViewController.present(self, animated: animated, completion: completion)
            }
        }
    
        private func newWindow() -> UIWindow {
            let window = UIWindow(frame: UIScreen.main.bounds)
            let rootViewController = UIViewController()
            rootViewController.view.backgroundColor = .clear
            window.backgroundColor = .clear
            window.rootViewController = rootViewController
            window.windowLevel = UIWindowLevelAlert
    
            return window
        }
    }
    

    You can then use this method to present your Alert Controller (or any UIViewController):

    alertViewController.presentFromNewWindow()
    

    When you dismiss the alert view controller, it is removed from the view controller and the window is removed from the hierarchy.