Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
    }
}
like image 877
Azhagusundaram Tamil Avatar asked Jun 30 '20 07:06

Azhagusundaram Tamil


2 Answers

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
    }

    [...]
}
like image 146
Matteo Pacini Avatar answered Oct 19 '22 13:10

Matteo Pacini


iOS 14.7

@main
struct TestApp: App {

    var window: UIWindow? {
        guard let scene = UIApplication.shared.connectedScenes.first,
              let windowScene = scene as? UIWindowScene else {
            return nil
        }
    
        return .init(windowScene: windowScene)
    }
}
like image 1
Boris Avatar answered Oct 19 '22 11:10

Boris