1

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?

D. Kee
  • 169
  • 14
  • 1
    Does this answer your question? [SwiftUI app life cycle iOS14 where to put AppDelegate code?](https://stackoverflow.com/questions/62538110/swiftui-app-life-cycle-ios14-where-to-put-appdelegate-code) – timbre timbre Jan 11 '23 at 19:26
  • See linked solution. It also shows how to setup firebase without appdelegate – timbre timbre Jan 11 '23 at 19:26
  • @flatasearth Please read the question again. The problem I have is a **result** of using exactly the same concept used in that link. – D. Kee Jan 11 '23 at 19:53

1 Answers1

1

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

lorem ipsum
  • 21,175
  • 5
  • 24
  • 48