Verify stored Firebase FCM tokens

前端 未结 1 739
悲哀的现实
悲哀的现实 2020-12-11 11:49

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

相关标签:
1条回答
  • 2020-12-11 12:48

    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.

    0 讨论(0)
提交回复
热议问题