iosswiftswiftuiappdelegateios14

How to use UIApplicationDelegateAdaptor as ObservableObject?


In my iOS 14 App, I can register the legacy AppDelegate by doing this:

@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

However, I noticed in the documentation you can make UIApplicationDelegateAdaptor an ObservableObject then it will inject it in the EnvironmentObject:

...delegate will be placed in the Environment and may be accessed by using the @EnvironmentObject property wrapper in the view hierarchy.

I couldn't find any example of how this would work. What is the syntax to making this work as an ObservableObject?


Solution

  • Here is a demo of usage:

    1. Conform AppDelegate to ObservableObject
    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
        }
    }
    
    1. Register your AppDelegate as adaptor as you did
    @main
    struct Testing_SwiftUI2App: App {
        @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
        // ... other code
    
    1. Declare @EnvironmentObject in some of your view, where needed
    struct ContentView: View {
        @EnvironmentObject var appDelegate: AppDelegate    // << inject
    
        var body: some View {
           Text("Value: \(appDelegate.value)")  // << use
        }
    }
    
    

    Tested with Xcode 12 / iOS 14.