0
我正在使用firebase雲功能向數據庫觸發器調用時向用戶發送通知。註冊令牌保存在firebase數據庫中。問題是,儘管註冊令牌得到了保存,通知並未顯示在這些設備中。 這是index.js通知不會顯示在數據庫觸發器上
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('/Blog').onWrite(event => {
const title = event.data.child('title').val();
const token_no = event.data.child('token_no').val();
const getDeviceTokensPromise = admin.database().ref(`/Token/${token_no}`).once('value');
const getBody=admin.database().ref(`/Blog`).once('value');
return Promise.all([getDeviceTokensPromise,getBody]).then(results => {
const tokensSnapshot = results[0];
const notify=results[1];
if (!tokensSnapshot.hasChildren()) {
return console.log('There are no notification tokens to send to.');
}
console.log('There are', tokensSnapshot.numChildren(), 'tokens to send notifications to.');
// Notification details.
const payload = {
notification: {
title: 'You have a new Alert!',
body: `${notify.child('title').val()}`,
}
};
// Listing all tokens.
const tokens = Object.keys(tokensSnapshot.val());
// Send notifications to all tokens.
return 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') {
tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
}
}
});
return Promise.all(tokensToRemove);
});
});
});
數據庫快照:
"Token" : {
"token_no" : {
"ctxjePemYZE:APA91bFJXXyTkyvXOlSY...4VbWu7Vbf7itwbwZu9umSvg_tdB1lKD1d8g" : "true",
"dgVszInjIW0:APA91bFZE3Av5unZTgp...RUeYb-CUhWjO1otqguhE9NTQZ8XgK6nRIW5" : "true"
}
}
你可以請檢查代碼是否正確,因爲我對JavaScript有一點了解。在運行編輯好的代碼後,它也會被執行,但是雲功能的日誌會顯示「沒有通知令牌要發送給」。 ,但令牌正在保存在數據庫中。我不確定代碼出錯的地方。 –
它仍然是一樣的!它仍然在日誌中顯示沒有令牌。我們必須創建FirebaseInstanceId來生成令牌,對吧?或者index.js會自動執行它? –
應用程序的每個實例都必須使用(例如)FirebaseInstanceId.getInstance()。getToken()來存儲它的標記並將其存儲在數據庫中。 –