背景
想要給iOS用戶(hù)推送一些信息柱锹,又不想使用極光啊拜鹤,友盟之類(lèi)的第三方推送SDK闽巩,畢竟是只針對(duì)iOS用戶(hù)的钧舌,并且用戶(hù)量不大,于是想到了自己建立推送服務(wù)器的想法涎跨。其實(shí)推送到iOS設(shè)備洼冻,大部分工作蘋(píng)果已經(jīng)為你做好了,所以我要做的工作比較少隅很,有以下幾點(diǎn):
- 推送到哪些設(shè)備?
- 這是需要從用戶(hù)的手機(jī)中收集的撞牢,當(dāng)用戶(hù)選擇安裝應(yīng)用并打開(kāi)它的推送功能時(shí),我們記錄下一個(gè)從蘋(píng)果服務(wù)器上返回的數(shù)據(jù),叫做DeviceToken
- 推送什么內(nèi)容?
- 內(nèi)容及部分及各式參見(jiàn)推送文檔
- 什么時(shí)候推送?
- 在服務(wù)器設(shè)定相應(yīng)的推送條件
推送到哪些設(shè)備
獲取DeviceToken以及相關(guān)推送的細(xì)節(jié)詳見(jiàn)喵神博客的活久見(jiàn)的重構(gòu) - iOS 10 UserNotifications 框架解析
推送什么內(nèi)容
使用Node.js推送
使用的是node-apn
推送的效果
"use strict";
const apn = require('apn');
let options = {
token: {
key: "p8證書(shū)",
// Replace keyID and teamID with the values you've previously saved.
keyId: "",
teamId: ""
},
production: false
};
let apnProvider = new apn.Provider(options);
// Replace deviceToken with your particular token:
let deviceToken = "deviceToken";
// Prepare the notifications
let notification = new apn.Notification();
notification.expiry = Math.floor(Date.now() / 1000) + 24 * 3600; // will expire in 24 hours from now
notification.badge = 1;
notification.sound = "ping.aiff";
// extra json dict
notification.payload = {"name":"xxx","img":"http://xxxx.jpg"};
// category name
notification.category = "saySomething"
notification.mutableContent = 1
notification.body = "this is content";
notification.title = "this is title"
notification.subtitle= "this is a subtitle"
// Replace this with your app bundle ID:
notification.topic = "bundleID";
// Send the actual notification
apnProvider.send(notification, deviceToken).then( result => {
// Show the result of the send operation:
console.log(result);
});
// Close the server
apnProvider.shutdown();
使用Python推送
使用的是改寫(xiě)過(guò)支持iOS10推送新特性的PyAPNs普泡,其中證書(shū)的導(dǎo)出參見(jiàn)自己動(dòng)手搭建蘋(píng)果推送Push服務(wù)器播掷,這里有個(gè)小坑就是,運(yùn)行的時(shí)候因?yàn)閷?dǎo)出的private.pem是有密碼的所以你要用一條命令將其的密碼取消掉撼班。
import time
from apns import APNs, Frame, Payload, PayloadAlert
apns = APNs(use_sandbox=True, cert_file='public.pem', key_file='private.pem')
# Send a notification
token_hex = 'devecetoken'
# payload = Payload(alert="Hello World!", sound="default", badge=1)
alert = PayloadAlert(title = 'title',subtitle = 'subtitle',body ='this is content')
payload = Payload(alert=alert, sound="default", badge=1, category = 'saySomething',custom={"name":"xxx","img":"http://xxx.jpg"}, mutable_content=True)
# payload.mutable_content = True
apns.gateway_server.send_notification(token_hex, payload)