首页 文章

颤振:Firebase推送数据变化

提问于
浏览
0

收到评论后,我已经将这个以下代码部署到我的firebase项目中并成功发布了!但是没有发送给我的通知 . 请查看我的Firebase实时数据库屏幕截图,以便更好地理解 .

[ITS SOLVED NOW:IT WILL SEND NOTIFICATIONS TO ONLY ONE ID ie My Admin Device]

工作代码:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firbase);
exports.codeformypeople = functions.database.ref('items/{id}').onWrite(evt => {

const payload = {
notification: { title: 'New Customer Requested', body: 'Touch to Open The App', badge: '1', sound: 'default', }
};
const token ="Lsn-bHfBWC6igTfWQ1-h7GoFMxaDWayKIpWCrzC";//replace with ur token

if (token) {
console.log('Toke is availabel .');
return admin.messaging().sendToDevice(token, payload);
} else {
console.log('token error');
}
});

[
Mydatabase Structure1

SEE THIS VIDEO LINK FOR MORE DETAILS

注意:如果你的应用程序被打开并且最小化,那么它将显示通知,但是如果应用程序被打开并且你正在使用,或者如果应用程序被终止强制关闭则它将无效!

1 回答

  • 2

    您可以使用firebase Cloud 功能来触发通知 . 以下是我用于触发通知的 Cloud 功能片段:

    const functions = require('firebase-functions');
    
    const admin = require('firebase-admin');
    admin.initializeApp(functions.config().firebase);
    
    exports.pushNotification = functions.database.ref('/Notifications/{pushId}')
     .onWrite(( change,context) => {
        console.log("Push Notification event triggered");
        var request = change.after.val();
        var payload = {
            data:{
                username: request.userName,
            }
        };
        admin.messaging().sendToDevice(request.userTokenId, payload)
        .then(function(response){
            console.log("Successfully sent message: ",response);
            console.log(response.results[0].error);
        })
        .catch(function(error){
            console.log("Error sending message: ", error)
        })
     })
    

    下面我提供了我的通知结构,您可以在下面看到 . 如果在数据库通知节点中推送任何新数据,该函数将触发 . 要查看触发此功能时输出/错误的内容,请访问firebase管理面板>功能>日志 .

    enter image description here

    您已完全部署了功能代码,但是您忘记在数据库中添加刷新tokenId,如上图所示我在我的数据库中保存 userTokenId 并在函数 admin.messaging().sendToDevice(request.userTokenId, payload) 中我正在使用该tokenId,此tokenId用于向特定发送通知设备,您可以使用 FirebaseInstanceId.getInstance().getToken() 获取此tokenId并将其保存在 fbproject1 > items 数据库结构中 . 请参考thisthis

相关问题