当应用程序 returns 到前台时删除任何弹出窗口

Removing any popover when app returns to foreground

假设:

这似乎是默认行为。请看下面的日历应用程序,我们从弹出窗口开始,转到后台,当打开应用程序时,弹出窗口仍然存在。

现在,我希望在打开应用程序时弹出窗口不存在(请不要问为什么,这是一个业务查询)。 我设法删除了将此代码放在方法

中的任何弹出窗口
- (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;
            }
            
        }

    }
}

它工作正常,返回前台时删除任何弹出窗口,但代码非常 hacky 并且依赖于 windowAlert 级别为 2000 的弹出窗口 UIWindow。

有更好的方法(更简单)来删除弹出框吗?

试试这个:

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