Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to retrieve token for FCM - iOS 10 Swift 3

i had implement Firebase with FirebaseAuth/FCM etc and did sent notification successfully through Firebase Console.

However i would need to push the notification from my own app server.

i am wondering below which way is correct way to retrieve the registration id for the device:-

1) retrieve registration id token from didRegisterForRemoteNotificationWithDeviceToken

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {     var token = ""      for i in 0..<deviceToken.count {         token += String(format: "%02.2hhx", arguments: [deviceToken[i]])     }      print("Registration succeeded!")     print("Token: ", token)     Callquery(token)  } 

2) Retrieve Registration token from firebase (Based on Firebase document which retrieve the current registration token)

let token = FIRInstanceID.instanceID().token()! 

i was using the first way, the push notification is not being received even the registration id is stored on my app server database accordingly and i get this CURL session result :-

{"multicast_id":6074293608087656831,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]} 

i had also tried the second way and get fatal error while running the app as below:- enter image description here

appreciated if anyone could point me the right way, thanks!

like image 902
aznelite89 Avatar asked Oct 13 '16 06:10

aznelite89


People also ask

Does FCM token change IOS?

Instead, you should expect that the device token can change at any time. Because your app might unexpectedly get a new token, you should record that token for the user every time your app launches.

How can I store FCM token in database?

Step1: as soon as you get token in callback whether new or same try to save it localstorage. Step2: Call your REST API to save it to your server. it is upto you if you want to send unique user identifier along with the token.

Is FCM token unique per device?

Yes, they are unique but they are not constant.


2 Answers

The tokenRefreshNotification function doesn't always get called when launching the app.

However, when placing the code inside the regular didRegisterForRemoteNotificationsWithDeviceToken delegate function, I can get the token every time:

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {     if let refreshedToken = InstanceID.instanceID().token() {         print("InstanceID token: \(refreshedToken)")     } } 

(Swift 3 + Firebase 4.0.4)

like image 61
Sam Avatar answered Sep 18 '22 11:09

Sam


The recommended way by Firebase:

let token = Messaging.messaging().fcmToken 

Reference : Setting Up a Firebase Cloud Messaging Client App on iOS

like image 26
Musa almatri Avatar answered Sep 20 '22 11:09

Musa almatri