FCM Keep token in sync

Viewed 251

So I using FCM with my Xamarin.Forms app. I'm a little confused on how can I maintain in sync the token generated in my app and the token stored in my app server.

Steps:

  1. Open the app.
  2. OnTokenRefresh() get a new token.
  3. The new token is send to the app server.
  4. The app server sends push notifications.

This works perfect, except, that time to time, FCM destroy the token, the app is not running (step 2 not firing), so my app server can't send messages anymore, because is out of sync.

Is there a way to update the FCM token to my app server without open the app?

1 Answers

The best way to remove tokens is when you try to use them to send a message. At that point the FCM API will tell you which tokens are invalid, and you can remove them fro your app server.

You can find an example of the code for this in the functions-example repo for sending message through FCM:

tokens = Object.keys(tokensSnapshot.val());
// Send notifications to all tokens.
const response = await admin.messaging().sendToDevice(tokens, payload);
// For each message check if there was an error.
const tokensToRemove = [];
response.results.forEach((result, index) => {
  const error = result.error;
  if (error) {
    functions.logger.error(
      'Failure sending notification to',
      tokens[index],
      error
    );
    // Cleanup the tokens who are not registered anymore.
    if (error.code === 'messaging/invalid-registration-token' ||
        error.code === 'messaging/registration-token-not-registered') {
      tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
    }
  }
});
return Promise.all(tokensToRemove);

So for each token the server returns messaging/invalid-registration-token or messaging/registration-token-not-registered this code removes that token from its database.

Related