自建APNS消息推送服务

背景

想要给iOS用户推送一些信息,又不想使用极光啊,友盟之类的第三方推送SDK,毕竟是只针对iOS用户的,并且用户量不大,于是想到了自己建立推送服务器的想法。其实推送到iOS设备,大部分工作苹果已经为你做好了,所以我要做的工作比较少,有以下几点:

  • 推送到哪些设备?
    • 这是需要从用户的手机中收集的,当用户选择安装应用并打开它的推送功能时,我们记录下一个从苹果服务器上返回的数据,叫做DeviceToken
  • 推送什么内容?
    • 内容及部分及各式参见推送文档
  • 什么时候推送?
    • 在服务器设定相应的推送条件

推送到哪些设备

获取DeviceToken以及相关推送的细节详见喵神博客的活久见的重构 - iOS 10 UserNotifications 框架解析

推送什么内容

使用Node.js推送

使用的是node-apn
推送的效果

"use strict";

const apn = require('apn');

let options = {
   token: {
     key: "p8证书",
     // 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推送

使用的是改写过支持iOS10推送新特性的PyAPNs,其中证书的导出参见自己动手搭建苹果推送Push服务器,这里有个小坑就是,运行的时候因为导出的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)

你可能感兴趣的:(自建APNS消息推送服务)