【发布时间】:2017-08-28 21:06:45
【问题描述】:
我正在尝试使用 node.js 向 Firebase 中的主题发送 iOS 推送通知。我关注了this tutorial,但无法弄清楚为什么通知没有发送到订阅该主题的设备。我可以从控制台发送主题消息,listenForNotificationRequests() 正在成功删除 notificationRequest 子项。
这是 Firebase 中通知请求的结构:
这里是删除了键/url 的 node.js 代码:
var firebase = require('firebase-admin');
var request = require('request');
var API_KEY = "APIKEYREMOVED"; // Your Firebase Cloud Messaging Server API key
// Fetch the service account key JSON file contents
var serviceAccount = require("./pathToJSON");
// Initialize the app with a service account, granting admin privileges
firebase.initializeApp({
credential: firebase.credential.cert(serviceAccount),
databaseURL: "URL_REMOVED"
});
ref = firebase.database().ref();
function listenForNotificationRequests() {
var requests = ref.child("notificationRequests");
requests.on("child_added", function(requestSnapshot) {
var request = requestSnapshot.val();
sendNotificationToUser(
request.username,
request.message,
function() {
requestSnapshot.ref.remove();
}
);
}, function(error) {
console.error(error);
});
};
function sendNotificationToUser(username, message, onSuccess) {
request({
url: "https://fcm.googleapis.com/fcm/send",
method: "POST",
headers: {
"Content-Type" : "application/json",
"Authorization": "key="+API_KEY
},
body: JSON.stringify({
to : "/topics/user_"+username,
priority : "high",
notification: {
title: message
}
})
}, function(error, response, body) {
if (error) { console.error(error); }
else if (response.statusCode >= 400) {
console.error('HTTP Error: '+response.statusCode+' - '+response.statusMessage);
}
else {
onSuccess();
}
});
}
// start listening
listenForNotificationRequests();
非常感谢任何帮助/建议!
编辑:
这是我订阅 Swift 主题的方式:
FIRMessaging.messaging().subscribe(toTopic: "user_\(currentUserID!)")
【问题讨论】:
-
NodeJS 代码看起来不错。您还可以输入您的客户端代码进行订阅吗?发送消息后是否收到成功响应?
-
'application/json'中有空格有关系吗?
-
@AL。添加了主题订阅的客户端代码。我已通过从控制台成功发送和接收主题消息确认订阅正常工作。我正在将 node.js 应用程序部署到 Google Cloud App Engine。仍在试图弄清楚如何在那里调试。那是我应该关注的地方吗?
-
@PeterTao 我已经部署了一个包含该空间的版本,但它没有解决我的问题。
-
本教程适用于安卓系统。你确定这适用于 iOS 吗?
标签: ios node.js firebase push-notification firebase-cloud-messaging