Ad

"didReceiveRegistrationToken" Does Not Give Me The FcmToken?

I'm building an app with firebase, and trying to save the FCM token for push notifications (which is sent by firebase functions).

The way I'm trying to do it is my storing the deviceToken in UserDefault, to use it later on.

I need to save the fcmToken when the user signs up (to store it in my database under profile).

When the user signs out, I need to delete the fcmToken in the database.

Because of this I have my func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) in AppDelegate (maybe this is wrong?), and I store it like this:

AppDelegate code:

func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {

        UserDefaults.standard.setValue("fcmToken", forKey: fcmToken)

}

When I want to call it, for example in the Sign Up viewcontroller, I declare the device token like this:

Sign Up ViewController code:

let deviceToken = UserDefaults.standard.value(forKey:"fcmToken") as? String ?? "not found"

And then i save it in my database like this

["fcmToken": deviceToken]

However, this always returns "not found" in Firebase, and does not save the actual device ID. It would be great if you guys could help me out on this one.

Ad

Answer

You have your "" backwards when saving to UserDefaults. the way you have it you're saving the string "fcmToken" under the fcmToken String

 func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {

    print(fcmToken)
    UserDefaults.standard.set(fcmToken, forKey: "fcmToken")

 }
Ad
source: stackoverflow.com
Ad