我一直在尝试为我的应用实现Cloud Messaging
,以便在将新的孩子添加到Realtime Database.
时,应用的每个用户都会自动收到通知
在我的MainActivity
中,我使用这种方法向每个用户订阅一个主题。
FirebaseMessaging.getInstance().subscribeToTopic("latest_events").addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
// Toast.makeText(MainActivity.this, "Successfully subscribed", Toast.LENGTH_SHORT).show();
}
});
我还为后端安装了firebase functions
并部署了JavaScript代码。
index.js
var functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref("/Users").onWrite(event => {
var payload = {
notification: {
title: "A new user has been added!",
body: "Click to see"
}
};
if (event.data.previous.exists()) {
if (event.data.previous.numChildren() < event.data.numChildren()) {
return admin.messaging().sendToTopic("latest_events", payload);
} else {
return;
}
}
if (!event.data.exists()) {
return;
}
return admin.messaging().sendToTopic("latest_events", payload);
});
添加用户时,我没有收到所需的通知。似乎无法理解做错了什么。
Firebase功能日志目录
sendNotification
TypeError: Cannot read property 'previous' of undefined at exports.sendNotification.functions.database.ref.onWrite.event (/user_code/index.js:15:19) at cloudFunctionNewSignature (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:105:23) at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:135:20) at /var/tmp/worker/worker.js:730:24 at process._tickDomainCallback (internal/process/next_tick.js:135:7)
答案 0 :(得分:0)
您正在使用Cloud Functions for Firebase的Beta版中的语法。由于它已更新为1.0,因此语法已更改,您将需要按照upgrade documentation中的说明更新代码以使其匹配。
将其应用于您的代码会导致如下所示:
var functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.sendNotification = functions.database.ref("/Users").onWrite((change, context) => {
var payload = {
notification: {
title: "A new user has been added!",
body: "Click to see"
}
};
if (change.before.exists()) {
if (change.before.numChildren() < change.after.numChildren()) {
return admin.messaging().sendToTopic("latest_events", payload);
} else {
return;
}
}
if (!change.after.exists()) {
return;
}
return admin.messaging().sendToTopic("latest_events", payload);
});
所做的更改是:
initializeApp
。before
中现在可以使用after
和change
快照。也请参见以下问题(searching for the error message很容易找到这些问题: