如何在iOS 14@main文件中获取UIWindow值?



我可以通过下面的实现访问didFinishLaunchingWithOptions。但是,我需要UIWindow变量。我不知道如何得到它。我使用的是 Xcode 12 beta。iOS14,SwiftUI 生命周期。


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
}
}

从 iOS 13 开始,可以安全地假设获取对密钥窗口的引用的正确方法是通过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
}
[...]
}

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)
}
}

最新更新