Kazuya Tomita
Kazuya Tomita

Reputation: 697

Firebase: How to translate a device token into a FCM token

I am trying to use the Firebase for push notifications. However, I have hit the block, namely I couldn't do that thing in iOS. I attempted two approaches of both

Messaging.messaging().setAPNSToken(deviceToken, type: .prod) and InstanceID.instanceID().setAPNSToken(deviceToken, type: InstanceIDAPNSTokenType.sandbox)

In 2nd

application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)

with Firebase imported.

What should I do?

EDIT: This is a supplemental information, the error message is like this. Failed to fetch default token Error Domain=com.firebase.iid Code=1003 "(null)" I googled, but there is no relavant information.

Upvotes: 1

Views: 3221

Answers (1)

Todd Kerpelman
Todd Kerpelman

Reputation: 17523

So you're close. Here's what happens right now in the Firebase 4.0 version of Cloud Messaging...

  1. When you call application.registerForRemoteNotifications(), iOS will request an APNs certificate, just like any ol' iOS app.

  2. Assuming you haven't turned method swizzling off (and you probably haven't), Firebase will automatically exchange that APNs token for an FCM token in its own swizzled didRegisterForRemoteNotificationsWithDeviceToken method.

  3. When that exchange is done, Firebase can let your app know. It used to be that the only way it did this was by creating an NSNotification of type kFIRMessagingRegistrationTokenRefreshNotification. But these days, it can also let you know through the MessagingDelegate. So the easiest thing to do is to declare your AppDelegate a messaging delegate by calling...

    Messaging.messaging().delegate = self
    

    ...and then implementing the messaging(_:didRefreshRegistrationToken) method.

    func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
      print("Look! I have an FCM token! \(fcmToken)")
    }
    

So the tl;dr is that you don't need to exchange the APNs token for an FCM token manually, you just need to set up your delegate to be notified when the FCM library does this for you.

Upvotes: 6

Related Questions