Swift – Get app keyWindow

Quick memo to get the keyWindow for all iOS versions until now.

KeyWindow is the “key” window of your entire application. The key window receives keyboard and other non-touch related events. Only one window at a time may be the key window.

Use the #available(iOS 13.0, *) keyword to bypass system check:

var keyWindow: UIWindow?

if #available(iOS 13.0, *) {
    keyWindow = UIApplication.shared.connectedScenes
        .filter({$0.activationState == .foregroundActive})
        .map({$0 as? UIWindowScene})
        .compactMap({$0})
        .first?.windows
        .filter({$0.isKeyWindow}).first
} else {
    keyWindow = UIApplication.shared.keyWindow
}

You can also use makeKey() to set the keyWindow to another UIWindow created and the makeKeyAndVisible()to make it active.

Enjoy.

 

Alberto Pasca

Software engineer @ Pirelli & C. S.p.A. with a strong passion for mobile  development, security, and connected things.