4

We have developed an app in iOS and Android which stores the FCM tokens in a database in order to send PUSH notifications depending on the user configuration.

Users install the app and the token of every device is stored in the database, so we would like to know what of those tokens are invalid because the app has been uninstalled.

On the other hand, we send the notifications through the website using JSON. Is there any limitation (I mean, is there any limit of elements in a JSON request)?

Thank you very much!

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Ugalde
  • 43
  • 2
  • 4

1 Answers1

12

I recently noticed that step 9 in the Cloud Functions codelab uses the response it gets from the FCM API to remove invalid registration tokens from its database.

The relevant code from there:

// Get the list of device tokens.
return admin.database().ref('fcmTokens').once('value').then(allTokens => {
  if (allTokens.val()) {
    // Listing all tokens.
    const tokens = Object.keys(allTokens.val());

    // Send notifications to all tokens.
    return admin.messaging().sendToDevice(tokens, payload).then(response => {
      // For each message check if there was an error.
      const tokensToRemove = [];
      response.results.forEach((result, index) => {
        const error = result.error;
        if (error) {
          console.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(allTokens.ref.child(tokens[index]).remove());
          }
        }
      });
      return Promise.all(tokensToRemove);
    });
  }
});

I quickly checked and this same approach is also used in the Cloud Functions sample for sending notifications.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thank you for your help. After following the steps starting at step 1, I see that (obviously) the Firebase SDK is needed but we have a Shared Server where we have no console to execute the lines. Is there any way to download the files and upload them? Thank you very much – Ugalde Mar 01 '18 at 17:23
  • If you don't have a trusted environment where you can run Node.js scripts or use one of the other Admin SDKs, you can run them on Cloud Functions as shown in both links that I shared in my answer. – Frank van Puffelen Mar 01 '18 at 18:47