如何使用 UIApplicationDelegateAdaptor 作为 ObservableObject?

Tru*_*an1 1 ios appdelegate swift swiftui ios14

在我的 iOS 14 中App,我可以AppDelegate通过执行以下操作来注册旧版:

@main
struct MyApp: App {
    
    #if os(iOS)
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    #endif
    
    var body: some Scene {
        ...
    }
}

#if os(iOS)
class AppDelegate: NSObject, UIApplicationDelegate {
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
        SomeSDK.configure(with: launchOptions)
        return true
    }
}
#endif
Run Code Online (Sandbox Code Playgroud)

但是,我在文档中注意到您可以制作UIApplicationDelegateAdaptor一个ObservableObject然后它将它注入到EnvironmentObject

...delegate 将被放置在 Environment 中,并且可以通过使用@EnvironmentObject视图层次结构中的属性包装器来访问。

我找不到任何有关如何工作的示例。使这项工作作为一个的语法是ObservableObject什么?

Asp*_*eri 6

这是一个使用演示

  1. 确认AppDelegateObservableObject
class AppDelegate: NSObject, UIApplicationDelegate, ObservableObject {
    @Published var value: String = ""

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {

        self.value = "test" // in any callback use your published property
        return true
    }
}
Run Code Online (Sandbox Code Playgroud)
  1. AppDelegate像您一样将您注册为适配器
@main
struct Testing_SwiftUI2App: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

    // ... other code
Run Code Online (Sandbox Code Playgroud)
  1. @EnvironmentObject在你的一些观点中声明,在需要的地方
struct ContentView: View {
    @EnvironmentObject var appDelegate: AppDelegate    // << inject

    var body: some View {
       Text("Value: \(appDelegate.value)")  // << use
    }
}

Run Code Online (Sandbox Code Playgroud)

使用 Xcode 12 / iOS 14 测试。