首页 > 解决方案 > SwiftUI 2 访问 AppDelegate

问题描述

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

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

po delegate印刷:

<MyProject.AppDelegate: 0x6000009183c0>

在哪里po UIApplication.shared.delegate打印:

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

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

提前致谢

标签: iosswiftuiappdelegate

解决方案


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

所以解决方案可能是:

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

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

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


推荐阅读