Cloud Functions For Firebase - Send Fcm Message To Multiple Tokens
I have to send a message to many token when a node is created in my realtime database. I use that's code, but any notification are lost (people not receive its). exports.sendMessa
Solution 1:
This is how you send a FCM to an array of tokens:
returnPromise.all([admin.database().ref(`/users/${user}/account/tokensArray`).once('value')]).then(results => {
const tokens = results[0];
if (!tokens.hasChildren()) returnnull;
let payload = {
notification: {
title: 'title',
body: 'message',
icon: 'icon-192x192.png'
}
};
const tokensList = Object.keys(tokens.val());
return admin.messaging().sendToDevice(tokensList, payload);
});
Solution 2:
You can send notifications to an array of tokens. I am using this code to send notifications
return admin.messaging().sendToDevice(deviceTokenArray, payload, options).then(response => {
console.log("Message successfully sent : " + response.successCount)
console.log("Message unsuccessfully sent : " + response.failureCount)
});
I think you can find more information here https://firebase.google.com/docs/cloud-messaging/admin/legacy-fcm
Solution 3:
To return a Promise for all the send actions, modify your code to this:
return query.once("value")
.then(function(snapshot) {
var allPromises = [];
snapshot.forEach(function(childSnapshot) {
var user = childSnapshot.val();
var token = user.token;
var username = user.username;
msg.message.token = token;
const promise = admin.messaging().send(msg.message).then((response) => {
console.log('message sent to '+username);
}).catch((error) => {
console.log(error);
});
allPromises.push(promise);
});
returnPromise.all(allPromises);
});
Post a Comment for "Cloud Functions For Firebase - Send Fcm Message To Multiple Tokens"