Firebase推送通知 - 节点工作者

Hol*_*bæk 6 javascript node.js ios firebase

我需要在将某个孩子添加到Firebase路径时向用户发送iOS推送通知.

我在想,最好的方法是在Heroku上创建一个Node.js工作人员,它会监听变化并使用Urban Airship发送通知.

我不确定从Heroku上的Node.js工作者那里听Firebase更改的最佳方法是什么.我不熟悉heroku worker和Node.js.

谁能给我一些指示?例子?

Dav*_*ast 4

使用 Firebase 和 node-apn 发送推送通知很简单:

var apn = require("apn");
var Firebase = require("firebase");

// true for production pipeline
var service = new apn.connection({ production: false }); 

// Create a reference to the push notification queue
var pushRef = new Firebase("<your-firebase>.firebaseio.com/notificationQueue");
// listen for items added to the queue
pushRef.on("child_added", function(snapshot) {

    // This location expects a JSON object of:
    // {
    //     "token": String - A user's device token
    //     "message": String - The message to send to the user
    // }
    var notificationData = snapshot.val();
    sendNotification(notificationData);
    snapshot.ref().remove();

});

function sendNotification(notificationData) {
    var notification = new apn.notification();
    // The default ping sound
    notification.sound = "ping.aiff";
    // Your custom message
    notification.alert = notificationData.message;
    // Send the notification to the specific device token
    service.pushNotification(notification, [notificationData.token]);
    // Clean up the connection
    service.shutdown();
}
Run Code Online (Sandbox Code Playgroud)

为了托管此脚本,您将无法使用 Heroku 等 PaaS。它们往往会杀死空闲的套接字。相反,您必须使用虚拟机。

Google Cloud Platform 有一个运行良好的 Node.js 启动器。