[iOS]Push Notification on iOS(2)

Build Provider Server for Push Notification on iOS

NodeJS+APN

1. Export .p12 from KeyChain for APS(+key).

  • Translate 2 p12 to pem

openssl pkcs12 -clcerts -nokeys -out apns-dev-cert.pem -in Certificates_aps_dev.p12

openssl pkcs12 -nocerts -out apns-dev-key.pem -in Certificates_private_key_aps_dev.p12

2.Install NodeJS on MacOS

3. Install APN module

npm install apn --save

Development

Sample Code

"use strict";

const apn = require("apn");

let tokens = ["5cdf34a5ceabc7be58aad8d7715facc81bc930fe4b49afa39d45437ff663a954"];

let service = new apn.Provider({
  cert: "/PathTo/apns-dev-cert.pem",
  key: "/PathTo/apns-dev-key.pem",
  gateway: "api.sandbox.push.apple.com",
  passphrase: "YOURPASSWORD" 
});

function randomNumber() {
    return parseInt(Math.random()*10000);
}

function simpleNotification() {
    let note = new apn.Notification();
    note.alert = { title:"Push Notification "+randomNumber(),
                   subtitle:'I am subtitle',
                   body:'I am body'
                         };
    note.topic = "YOURBUNDLEID";
    note.badge = 1;
    note.payload = {name:'Tom'};
    note.expiry = Math.floor(Date.now() / 1000) + 3600; // Expires 1 hour from now.
    
    return note;
}

function silentNotification() {
    let note = new apn.Notification();
    note.contentAvailable = true;
    note.topic = "YOURBUNDLEID";
    note.payload = {name:'Tom'};
    note.expiry = Math.floor(Date.now() / 1000) + 3600; // Expires 1 hour from now.
    return note;
}

process.argv.forEach((val, index) => {
    console.log(`${index}: ${val}`)
  })
const mode = process.argv[2];

const simpleNote = simpleNotification();
const silentNote = silentNotification();
let note;
if (mode === 'silent') {
    note = silentNote;
} else {
    note = simpleNote;
}
console.log(`Sending: ${note.compile()} to ${tokens}`);
service.send(note, tokens).then( result => {
    console.log("sent:", result.sent.length);
    console.log("failed:", result.failed.length);
    console.log(result.failed);
});

service.shutdown();
 

Run it!

node src/pushnotification/apns.js simple
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章