SwiftUI 2 访问 AppDelegate

SwiftUI 2 accessing AppDelegate

我做了一个小原型,它使用 Firebase 云消息传递和新的 SwiftUI 2 应用程序生命周期。我通过添加自定义 AppDelegate @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate 并禁用了 FCM 工作的方法调配。一切都按预期工作。

今天一位同事问我,是否可以通过UIApplication.shared.delegate获取委托对象。所以我试了一下,发现似乎有两个不同的 AppDelegate 对象:

po delegate 打印:

<MyProject.AppDelegate: 0x6000009183c0>

其中 po UIApplication.shared.delegate 打印:

▿ Optional<UIApplicationDelegate>
  ▿ some : <SwiftUI.AppDelegate: 0x600000b58ca0>

现在我想知道访问 AppDelegate 的正确方法是什么?是否应该通过 @EnvironmentalObject 获取它并将其传递给所有视图?或者通过 UIApplication 使用老式的方式? 此外,我想了解为什么我最终得到两个 AppDelegates。

提前致谢

您的 MyProject.AppDelegate 不是直接的 UIApplicationDelegate,它通过适配器传输到内部私有 SwiftUI.AppDelegate,这是真实的 UIApplicationDelegate 并且将一些委托回调传播到您的实例。

所以解决方案可能是:

  1. 如果您只需要在 SwiftUI 视图层次结构中访问 MyProject.AppDelegate,请使用 @EnvironmentalObject

  2. 添加并使用 MyProject.AppDelegate static 属性,它使用通过适配器创建的对象进行初始化,例如

class AppDelegate: NSObject, UIApplicationDelegate {
    static private(set) var instance: AppDelegate! = nil
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        AppDelegate.instance = self    // << here !!
        return true
    }
}

现在,在您的代码中的任何地方,您都可以通过 AppDelegate.instance 访问您的委托。