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

9

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

那个时候还没有窗口,你为什么需要它呢? - Asperi
我想集成一个SSO SDK。我们需要使用UIWindow(根视图控制器)初始化SDK。之前(Swift UI 1.0),我从SceneDelegate获取了UIWindow。 - Azhagusundaram Tamil
2个回答

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

    [...]
}

1
太棒了。谢谢。 - Azhagusundaram Tamil
5
如果只有一个窗口和一个场景,这可能只能起作用。也就是说,在iPad上进行多任务处理或在macOS上进行处理时,它将无法起作用。 - Nicolai Henriksen
很棒,除了在App::init中它无法工作。 - Anton Tropashko

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

请添加一些解释。 - de.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接