如何在带有场景的项目中修复 AppDelegate 的 window == nil?

How to fix AppDelegate's window == nil in project with scenes?

还有一些类似的问题,但都是关于项目使用场景时如何获取window。但我的略有不同。

您建议通过不同的方式获得活动 window - 可以。但是如何处理旧库(在我的例子中是自定义 activity 视图),它可以使用 "implicitly unwrapping" 访问可选的 window 属性: appDelegate.window!

是否可以将 appDelegate.window 属性 getter 覆盖为 return 当前的 window?

这是可能的方法

1) 在应用委托

中声明window属性
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    ...

2) 在window showing (or creation, which place is preferred)

场景中明确赋值
  func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        ...
        window.makeKeyAndVisible()
        if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
            appDelegate.window = window
        }