ambassador
ambassador

Reputation: 444

How to access data in AppDelegate from ObservableObject class in SwiftUI

With the new SwiftUI Lifecycle there normally is no AppDelegate anymore. However, in order to implement Firebase Messaging, it is recommended on the Firebase docs to implement an AppDelegate and attach it using:

@main
struct ExampleApp: SwiftUI.App {
    
    // register app delegate for Firebase setup
    @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate //<--- HERE
    
    @StateObject var appState = AppState()

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(appState)
        }
    }
}

Inside this AppDelegate functions one obtains an FCM Token, with which the device is identified to subsequently send it notifications remotely. This token has to get sent to the server. This could be done inside the respective function inside the AppDelegate . However, there is a class AppState (ObservableObject protocol) that handles the user data and writing to the server, so it would make a lot more sense to write pass it to this class (or retrieve in the class from the AppDelegate?) and then push it from there.

How can this be accomplished?

edit: I guess this could be achieved by using a static property in the AppDelegate as described in this answer. Is using statics to access variables globally not bad practice? Is there a other (better) way?

Upvotes: 2

Views: 672

Answers (1)

lorem ipsum
lorem ipsum

Reputation: 29614

You can do it with the "old way" of accessing the delegate

@MainActor //Required by the app delegate
class AppState: ObservableObject{
    lazy var appDelegate: AppDelegate? = {
        UIApplication.shared.delegate as? AppDelegate
    }()
}

Then you can just use

appDelegate?.yourToken

yourToken referencing a property in the delegate

Upvotes: 2

Related Questions