SwiftUI 2 accessing AppDelegate



我做了一个小原型,使用Firebase云消息和新的SwiftUI 2应用程序生命周期。我添加了一个自定义AppDelegate via@UIApplicationDelegateAdaptor(AppDelegate.self) var delegate和禁用方法搅拌FCM工作。一切正常

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

po delegateprints:

<MyProject.AppDelegate: 0x6000009183c0>

其中po UIApplication.shared.delegate打印:

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

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

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

所以解决方案可能是:

  1. 如果你只需要在SwiftUI视图层次结构中访问MyProject.AppDelegate,请使用@EnvironmentalObject(为此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
}
}

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

最新更新