Friday, February 19, 2016

iOS shows alert view independent of current viewcontroller

Usually when displaying alert view on ios, it is presented by the current topmost viewcontroller. However, sometime, the current topmost presented viewcontroller may not be easy to get , or the current presented viewcontroller may get dismissed while the new alertview is displayed.

To handle the issue, one option is create a new UIWindow object and make it visible, then create a empty root viewcontroller for the UIWindow. Then show the alert view on top of the new UIWindow's root viewcontroller. This approach can show the uialert view regardless which viewcontroller is currently shown by other part of application logic.

The sample code is shown below:
        __block UIWindow* win= [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        win.rootViewController = [[UIViewController alloc] init];
        win.windowLevel = UIWindowLevelAlert + 1;
        [win makeKeyAndVisible];
        UIAlertController* alert = [UIAlertController
                                    alertControllerWithTitle:@"Change Password"
                                    message:@"The password has been updated, click OK to reload the page."
                                    preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction
                                        actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                        handler:^(UIAlertAction * action) {
                                            [self reloadStartUrl];
                                            win.rootViewController = nil;
                                            win.hidden = true;
                                            win = nil;

                                        }];
        
        [alert addAction:defaultAction];

        [win.rootViewController presentViewController:alert animated:YES completion:nil];
        

No comments:

Post a Comment