2

我希望每次在Firebase数据库中创建新子项时都会收到通知。这是我到目前为止。使用这行代码,您可以在创建新的孩子时收到通知。但问题是,通知总是与标题:“标题”,身体:“来检查它”是。现在是我的问题,我怎么可以创建一个通知与价值城市和时间(请参见下面的结构)将新的子项添加到数据库时Firebase推送通知

const functions = require('firebase-functions'); 
const admin = require('firebase-admin'); 
admin.initializeApp(functions.config().firebase); 

exports.sendPushNotification = functions.database.ref('/Rollerbanken/{Id}').onCreate(event => { 

    const payload = { 
    notification: { 
    title: 'Title', 
    body: 'come check it', 
    badge: '0', 
    sound: 'default', 
    } 
}; 
    return admin.database().ref('fcmToken').once('value').then(allToken => { 
    if(allToken.val()) { 
    const token = Object.keys(allToken.val()); 
    return admin.messaging().sendToDevice(token, payload).then(response => { 
      }); 
     }; 
    }); 
}); 

我的结构:

{ 
    "Rollerbanken" : { 
    "-KuKDXL2pY9MMtw551ZI" : { 
     "Extrainformatie" : "", 
     "Latitude" : "51.9145932124898", 
     "Longitude" : "5.86974696138047", 
     "Staater" : "Staat er", 
     "Staaternietmeer" : "", 
     "City" : "Overbetuwe", 
     "Time" : "15 : 43", 
     "TijdControle" : "15 : 43", 
     "TijdControleniet" : "", 
     "TypeControle" : "Rollerbank" 
    } 
    } 

我希望你能帮帮我!

+0

您可能需要查看Firebase的Cloud Functions并编写数据库触发器,该数据库触发器使用admin SDK在数据库中的某个位置发生更改时发送通知。 https://firebase.google.com/docs/functions/ –

回答

0

基本上,您需要修改您希望发送的每个通知的有效负载对象。好消息是,因为它只是一个你可以轻松访问的对象,所以你所要做的就是payload.name = YOURDESIREDVALUEHERE

所以你需要做的是把你的新密钥(令牌),并用它来访问你的对象。除非我记错了Object.keys生成数组,所以你的快捷键应该是令牌[0],然后用它来访问你的价值,像这样allToken.val()[token[0]]["City"]

您的代码应该是这样的:

const functions = require('firebase-functions'); 
const admin = require('firebase-admin'); 
admin.initializeApp(functions.config().firebase); 
exports.sendPushNotification = functions.database.ref('/Rollerbanken/{Id}').onCreate(event => { 

    const payload = { 
    notification: { 
    title: 'Title', 
    body: 'come check it', 
    badge: '0', 
    sound: 'default', 
    } 
}; 
    return admin.database().ref('fcmToken').once('value').then(allToken => { 
    if(allToken.val()) { 
    const token = Object.keys(allToken.val()); 
    payload.notification.title = allToken.val()[token[0]]["City"] + allToken.val()[token[0]]["Time"] //change here 
    return admin.messaging().sendToDevice(token, payload).then(response => { 
      }); 
     }; 
    }); 
}); 
+0

它不再发送任何通知。 –

+0

其原因我搞砸了,我会编辑 – TheCog

+0

它仍然无法正常工作。 –