iosswiftswiftuixcode12ios14

How to get UIWindow value in iOS 14 @main file?


I can able to access didFinishLaunchingWithOptions by below implementation. But, I need UIWindow variable. I don't know how to get it. I'm using Xcode 12 beta. iOS14, SwiftUI lifecycle.


import SwiftUI

@main
struct SSOKit_DemoApp: App {
    
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

class AppDelegate: NSObject, UIApplicationDelegate {
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        
        print("hello world!!!")
        return true
    }
}

Solution

  • From iOS 13 onwards, it's safe to assume that the correct way to obtain a reference to the key window is via UIWindowSceneDelegate.

    @main
    struct DemoApp: App {
        
        var window: UIWindow? {
            guard let scene = UIApplication.shared.connectedScenes.first,
                  let windowSceneDelegate = scene.delegate as? UIWindowSceneDelegate,
                  let window = windowSceneDelegate.window else {
                return nil
            }
            return window
        }
    
        [...]
    }