Firebase push notifications - node worker

后端 未结 1 1622
面向向阳花
面向向阳花 2020-12-14 13:36

I need to send iOS push notifications to user whenever a certain child is added to a Firebase path.

I was thinking, that the best way to do that, would be to make a

相关标签:
1条回答
  • 2020-12-14 13:47

    Sending push notifications with Firebase and node-apn is easy:

    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();
    }
    

    For hosting this script, you won't be able to use a PaaS like Heroku. They tend to kill idle sockets. Instead you'll have to use a virtual machine.

    Google Cloud Platform has a Node.js launcher that works well.

    0 讨论(0)
提交回复
热议问题