Search code examples
iosswiftappdelegateuiscenedelegate

Accessing UIWindow instance in Xcode 11.3 when target is ios 11.0 or letter


The problem is I'm using Xcode 11 which has the new AppDelegate / SceneDelegate setup. Because of this, the UIWindow is nil, so the new rootViewController is not set. I know that in iOS 13 the window is accessed in the SceneDelegate, but this project's target is iOS 11 or letter.The SceneDelegate class has been proceeded by @available(iOS 13.0, *). How can I access UIWindow from the appDelegate? I'm working with Xcode 11.3 and Swift 5.0.


Solution

  • Here is the extension that i am using in my project

    extension UIWindow {
        static var key: UIWindow? {
            if #available(iOS 13, *) {
                return UIApplication.shared.windows.first { $0.isKeyWindow }
            } else {
                return UIApplication.shared.keyWindow
            }
        }
    }
    

    This is how you use this extension

    if let getWindow = UIWindow.key {
        // use getWindow to perform action on window
    }