Removing any popover when app returns to foreground

Viewed 128

Let's say:

  • we have an app and we have a popover on the current screen:
  • we tap the Home button on the iPad and app goes to background
  • we open again the app On opening the app, the popover will be present.

This seems to be the default behaviour. See below the Calendar app, we start with a popover, go to background and when opening the app, the popover is still present.

enter image description here

Now, I want that on opening the app the popover is not present (please dont ask why, it is a bussiness query). I managed to remove any popover placing this code in the method

- (void)applicationWillEnterForeground:(UIApplication *)application {

  NSArray         *windows = [[UIApplication sharedApplication]windows];
    for (UIWindow   *window in windows) {
        if (window.windowLevel == 2000) {
            window.hidden = YES;
            if (@available(iOS 13.0, *)) {
                window.windowScene = nil;
            }
            
        }

    }
}

It works ok, removing any popup when returning to foreground, but the code is very hacky and relies on popover UIWindow having a windowAlert level of 2000.

There is a better way (less hacky) to remove the popover?

1 Answers

Try this:

- (void)applicationWillEnterForeground:(UIApplication *)application {
    UIViewController *vc = self.window.rootViewController;
    while (vc.presentedViewController) {
        vc = vc.presentedViewController;
        [vc dismissViewControllerAnimated:false completion:nil];
    }
}
Related