How to remove a UIWindow?

This extension helped me in some more cases:

/// Removes window from windows stack
func remove() {
    rootViewController?.view.removeFromSuperview()
    rootViewController = nil
    isHidden = true
    
    // https://stackoverflow.com/a/59988501/4124265
    if #available(iOS 13.0, *) {
        windowScene = nil
    }
}

Do not invoke -resignKeyWindow directly, it was meant to be overridden to execute some code when your UIWindows gets removed. In order to remove old window you need to create new instance of UIWindow and make it -makeKeyAndVisible, the old window will resign its key status. In iOS 4 it will even garbage collect your old UIWindow, provided you don't have any references to it. Doing this in iOS 3.x would have disastrous effects. Warned ya.


Here is how you can remove UIWindow on iOS 13 in a backward-compatible way. Tested on iOS 12, iOS 13, iPadOS with multi-window support:

extension UIWindow {
    func dismiss() {
        isHidden = true

        if #available(iOS 13, *) {
            windowScene = nil
        }
    }
}

Usage:

// Detect key window
let keyWindow = UIApplication.shared.windows.first { $0.isKeyWindow }

// Dismiss key window (if any)
keyWindow?.dismiss()

The correct way to hide a window is to set the hidden property to YES. To remove it from UIApplication's windows property you just release the window (in ARC you set all references to nil).

Of course you would want to have another window in place at this time.