2014-06-05 24 views
1

所以,我上的PhoneGap,我使用:Phonegap PushNotification,如何使用具有phonegap的節點推送服務器?

所以,我安裝了第一個插件,我可以得到我的手機令牌。在那之後,我創建了一個節點server.js文件在我的根目錄有:

var apn = require('apn'); 

var token = "MY TOKEN"; 
var device = new apn.Device(token); 

var notification = new apn.Notification(); 
notification.expiry = Math.floor(Date.now()/1000) + 3600; 
notification.badge = 1; 
notification.alert = "This is a Push Notification=)"; 
notification.payload = {'prop': 'special value'}; 
notification.device = device; 

var options = { 
gateway: 'gateway.sandbox.push.apple.com', 
cert: 'CER.pem', 
key: 'KEY.pem', 
passphrase: 'password' 
} 
var apnsConnection = new apn.Connection(options); 
apnsConnection.pushNotification(notification, device); 

當我開始我的服務器node server.js在命令行中,我可以看到我的手機在我的推送通知,因此,所有它的確定。

但我的問題,我需要在我的代碼(phonegap)不同的地方發送推送通知。我怎樣才能做到這一點 ?

當我的server.js正在運行時,如何從我的phonegap應用程序發送其他推送通知?

回答

0

你上面的代碼是你可以收集在一起,並公開一個函數多次調用它。例如,一個非常簡單的實現將是:

var apn = require('apn'); 
var options = { 
    gateway: 'gateway.sandbox.push.apple.com', 
    cert: 'CER.pem', 
    key: 'KEY.pem', 
    passphrase: 'password' 
}; 
var apnsConnection = new apn.Connection(options); 

module.exports.pushNotification = function(token, alert) { 
    var device = new apn.Device(token); 

    var notification = new apn.Notification(); 
    notification.alert = alert; 
    notification.device = device; 

    apnsConnection.pushNotification(notification, device); 
}; 

想象一下,你的名字「推送通知服務」這個文件pns.js。現在,在您server.js,你可以改爲require該模塊剛創建並調用pushNotification功能:

var pns = require("./pns.js"); 

pns.pushNotification("MY TOKEN", "This is a Push Notification"); 

現在你已經得到了同樣的功能,當你執行server.js。從這裏開始,你可以把這個函數放到其他需要從Node.js端調用它的模塊中。

如果您需要從遠程進程調用它,您可以查看像Express這樣的Web框架,並構建一個調用相同代碼的API。令牌和警報消息可以被傳遞給這個函數調用。這樣做可能會將您的server.js轉變爲正在運行的Web服務器,該服務器將偵聽請求並按需發送推送通知。

0

有點晚了,但人們同樣的問題,看看這個工具:

https://www.npmjs.com/package/node-pushserver

...它正是你想要的。它支持iOS和Android。

在服務器上運行此應用程序,您的應用程序可以:通過POST到http://yourserver:8000:/subscribe註冊設備。設備存儲在一個mongodb數據庫中。通過將http請求發佈到http://yourserver:8000/send,您可以將推送通知發送到單個註冊的設備,其子集或全部。

玩得開心!