自建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)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 极光推送: 1.JPush当前版本是1.8.2,其SDK的开发除了正常的功能完善和扩展外也紧随苹果官方的步伐,SD...
    Isspace阅读 6,770评论 10 16
  • 推送通知,是现在的应用必不可少的功能。那么在 iOS 中,我们是如何实现远程推送的呢?iOS 的远程推送原理又是什...
    皮皮瑞阅读 1,306评论 0 3
  • 前言 我们在实现推送功能的时候,更需要了解下推送的原理机制,这样我们在发现问题时候才好定位到问题的解决办法。 推送...
    進无尽阅读 3,890评论 0 5
  • 方法一: 找到.gitconfig,添加如下配置。(或者用git config --global命令) 方法二: ...
    iYeso阅读 3,187评论 0 7
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,206评论 4 61