Reputation: 1943
I am using Cloud Firestore to keep app tokens to send push notifications. However, when the user uninstalls and reinstalls the app, Firestore receives a different token for the same user. How can I delete the relevant row of the previous token when the user uninstalls the app?
Thanks in advance.
Upvotes: 2
Views: 2528
Reputation: 600131
Usually you'll want to detect when a token becomes invalid, and remove it at that time. E.g. when a token gets cycled (which happens every few weeks while the user has the app installed), you'll want to use that moment to remove the old token from your database and add the new one. Doing so minimizes the number of outdated tokens you have in your database.
So in steps that means in onTokenRefresh()
:
Check if there is a token in local storage (e.g. shared preferences). If so, remove that token from both the database and local storage.
Store the new token in both the database and local storage.
But in your case that is not possible, since onTokenRefresh
won't be called when the app is uninstalled, and you won't have knowledge of the previous token when it gets reinstalled.
The easiest way to deal with outdated tokens left behind in this and other ways is to delete them when sending to that token fails. The sample of sending FCM notifications using Cloud Functions has a good example of that:
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') {
tokensSnapshot.ref.child(tokens[index]).remove();
}
}
});
});
Upvotes: 9
Reputation: 1
It's quite simple, when the user reinstalls the app and logs in again, just override the old token with the new one. If you have also other stuff that needs to be deleted once the new token is generated, just check the existing token with the new one. If the tokens are different, you may delete all the unnecessary stuff.
Upvotes: 1