在所有内容之上呈现一个 UIAlertController 并保持在顶部,即使另一个视图被推送 (iOS 13)

Present an UIAlertController on top of everything and stay on top even if another view is pushed (iOS 13)

我正在尝试实现一个显示在 window 之上的 UIAlertController 并保持这种状态直到用户关闭它,即使应用程序试图推送另一个视图控制器也是如此。

我已经阅读了这些问题和答案:

虽然在 iOS 13 之前的版本中提供的解决方案非常有效,但我一直试图在 iOS 13 中解决此问题:

当我显示 UIAlertController 时,它会保持在顶部,直到另一个视图控制器被推入导航堆栈。如果发生这种情况,UIAlertController 将消失。

func showHighPriorityNotification() {
    let alertWindow = UIWindow(frame: UIScreen.main.bounds)
    alertWindow.rootViewController = UIViewController()
    alertWindow.windowLevel = UIWindowLevelAlert + 1
    alertWindow.makeKeyAndVisible()

    let alertController = UIAlertController(title: "Title"), message: "Message"), preferredStyle: .alert)
    alertController.addAction(UIAlertAction(title: "Button"), style: .default))

    if #available(iOS 13, *) {
        // Trying to get this functionality to work in iOS 13.
        if var topController = alertWindow.rootViewController {
            while let presentedViewController = topController.presentedViewController {
                topController = presentedViewController
            }
            topController.modalPresentationStyle = .fullScreen
            topController.present(alertController, animated: true)
        }
    } else {
        // This code works in iOS 12 and below, but NOT in iOS 13.
        alertWindow.rootViewController?.present(alertController, animated: true)
    }
}

在 iOS13 中,是否有某种方法可以将 UIAlertController 保持在顶部并允许将视图推到其下方?正如我所说,在以前的版本中,这很好用。

您可以使用在 iOS 12 及以下版本中使用的相同实现,但您必须强烈引用要显示警报的 window。

在您当前的代码中 - 当 运行 在 iOS 13 时 - alertWindow 将在 showHighPriorityNotification 完成后立即销毁,从而消除您的警报。它可以通过在其他地方持有对 alertWindow 的强引用来修复。

查看 以了解实现方法。