'How to get Firebase FCM token outside the Swift AppDelegate

I have a SwiftUI app and inside it's custom AppDelagte I get the FCM token and save it to my database. Which works.

But when the user registers and gets put to the main screen of the applcation, their FCM token isn't uploaded to the database until they restart the app and the AppDelagte messaging function is run again. So basically, when the user registers, the app will not function correctly until they restart the app.

I have tried to get and then send the FCM token as soon as they successfully register via:

Messaging.messaging().fcmToken

which returns an empty string, meaning it is only made after they re run the app delegate.

How do I get around this, and send the FCM token to their database profile as soon as they register?



Solution 1:[1]

You can use this method at any time to access the token instead of storing it.

Messaging.messaging().token { token, error in
  if let error = error {
    print("Error fetching FCM registration token: \(error)")
  } else if let token = token {
    print("FCM registration token: \(token)")
    self.fcmRegTokenMessage.text  = "Remote FCM registration token: \(token)"
  }
}

https://firebase.google.com/docs/cloud-messaging/ios/client

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Neznayka