Search code examples
iosswiftappdelegateuiwindow

Why is AppDelegate.swift window an optional?


I was reading Apple docs, when I found this sentence:

The AppDelegate class contains a single property: window.

var window: UIWindow?

This property stores a reference to the app’s window. This window represents the root of your app’s view hierarchy. It is where all of your app content is drawn. Note that the window property is an optional, which means it may have no value (be nil) at some point.

What I don't understand is: why this property at some point could be nil? What's the case for it to be(come) nil?


Solution

  • When you close your application, your app can still receive silentNotifications or download data in the background, track your location, play music, etc.

    In the images below, the encircled red are for when your app is still doing something, however it is no longer on the screen. It's in the background, so AppDelegate doesn't need a window anymore. As a result it will be set to nil

    Simple overview

    enter image description here


    Detail overview

    enter image description here

    FWIW, the code below won't make the app launch with vc.

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
            let vc = ViewController()
            window?.rootViewController = vc
            window?.makeKeyAndVisible()
            return true
        }
    

    Why it doesn't work? Because the window property is an optional—initially set to nil.It needs to be instantiated

    The code below will work

     func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        let vc = ViewController()
        window = UIWindow(frame: UIScreen.main.bounds) // Now it is instantiated!!
        window?.rootViewController = vc
        window?.makeKeyAndVisible()
        return true
    }