【问题标题】:How can I send Firebase notifications using cloudfunctions on firebase database datachange? [closed]如何在 Firebase 数据库数据更改时使用云功能发送 Firebase 通知? [关闭]
【发布时间】:2019-03-31 02:10:11
【问题描述】:
如果 firebase 数据库值发生更改,我正在尝试创建云功能,然后我发送 firebase 通知?下面是我的 firebase 数据库快照...就像我想发送有关 liveurl 更改的通知
livestream
|_
liveurl: "https://www.youtube.com/watch?v=Z8agqyGIaD8"
【问题讨论】:
标签:
android
firebase
firebase-realtime-database
firebase-cloud-messaging
google-cloud-functions
【解决方案2】:
试试这个云功能:
exports.sendNotification = functions.database.ref('/livestream/{liveurl}').onUpdate((data, context) => {
const liveurl = context.params.liveurl;
//getting the instance of the target user. this instance object will contain the device token of the target user
return admin.database().ref(`/apps/${app_id}/users/${sender_id}/instances`).once('value').then(function(instancesIdAsObj) {
const tokens = Object.keys(instancesIdAsObj.val());
const payload = {
notification: {
title: sender_fullname,
body: text,
icon : "ic_notification_small",
sound : "default",
click_action: "NEW_MESSAGE",
"content_available": "true",
badge : "1"
},
data: {
liveurlString: liveurl,
}
};
return admin.messaging().sendToDevice(tokens, payload).then(function (response) {
console.log("Push notification for message "+ JSON.stringify(message) + " with payload "+ JSON.stringify(payload) +" sent with response ", JSON.stringify(response));
return error;
}
});
})
.catch(function (error) {
console.log("Error sending message:", error);
return 0;
});
});
});