SwiftUI 2 访问 AppDelegate

Car*_*ten 11 ios appdelegate swiftui

我做了一个小型原型,它使用 Firebase Cloud Messaging 和新的 SwiftUI 2 应用程序生命周期。我添加了一个自定义 AppDelegate via\n@UIApplicationDelegateAdaptor(AppDelegate.self) var delegate并禁用了方法调配以使 FCM 能够工作。一切都按预期进行。

\n

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

\n

po delegate印刷:

\n
<MyProject.AppDelegate: 0x6000009183c0>\n
Run Code Online (Sandbox Code Playgroud)\n

其中po UIApplication.shared.delegate打印:

\n
\xe2\x96\xbf Optional<UIApplicationDelegate>\n  \xe2\x96\xbf some : <SwiftUI.AppDelegate: 0x600000b58ca0>\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n

Asp*_*eri 26

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

所以解决方案可能是:

  1. @EnvironmentalObject如果您需要访问MyProject.AppDelegate仅在 SwiftUI 视图层次结构中使用(因为这AppDelegate必须符合ObservableObject)。

  2. 添加并使用MyProject.AppDelegate静态属性,该属性是通过适配器创建的对象初始化的,例如

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
    }
}
Run Code Online (Sandbox Code Playgroud)

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