如何获取 iOS 14 @main 文件中的 UIWindow 值?
How to get UIWindow value in iOS 14 @main file?
我可以通过以下实现访问 didFinishLaunchingWithOptions。但是,我需要 UIWindow 变量。我不知道如何得到它。我正在使用 Xcode 12 测试版。 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 开始,可以安全地假设获取对密钥 window 的引用的正确方法是通过 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)
}
}
我可以通过以下实现访问 didFinishLaunchingWithOptions。但是,我需要 UIWindow 变量。我不知道如何得到它。我正在使用 Xcode 12 测试版。 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 开始,可以安全地假设获取对密钥 window 的引用的正确方法是通过 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)
}
}