5

我可以通过以下实现访问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
    }
}
4

2 回答 2

14

从 iOS 13 开始,可以安全地假设获取对关键窗口的引用的正确方法是 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
    }

    [...]
}
于 2020-06-30T11:51:03.560 回答
0

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)
    }
}
于 2021-07-21T20:23:45.520 回答