所以,我在 Phonegap 上,我使用:
所以,我安装了第一个插件,我可以获得我的手机 token 。之后,我在根目录中创建了一个 Node 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应用程序发送其他推送通知?
最佳答案
上面的代码可以收集在一起,并公开一个函数以多次调用它。例如,一个非常简单的实现是:
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。然后可以将 token 和警报消息传递给此函数调用。这样做可能会将您的 server.js
变成一个正在运行的 Web 服务器,用于监听请求并根据需要发送推送通知。
关于javascript - Phonegap PushNotification,如何将我的 Node 推送服务器与phonegap一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24063263/