Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
424 views
in Technique[技术] by (71.8m points)

ios - 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?

question from:https://stackoverflow.com/questions/65918503/how-to-get-firebase-fcm-token-outside-the-swift-appdelegate

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could store the fcmToken on a static property of the AppDelegate as soon as you get it and then access it whenever the user registers.

Add a static property to the app delegate:

class AppDelegate: UIResponder, UIApplicationDelegate {
    static var fcmToken: String?

    // when you get the token set it to the static property
    Self.fcmToken = fcmToken
}

Then when you need the token simply access:

AppDelegate.fcmToken

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...