一、消息推送的原理
Provider是指某个iPhone软件的Push服务器,APNS是Apple Push Notification Service的缩写,是苹果的服务器。
上图可以分为三个阶段:
第一阶段:应用程序把要发送的消息、目的iPhone的标识打包,发给APNS。
第二阶段:APNS在自身的已注册Push服务的iPhone列表中,查找有相应标识的iPhone,并把消息发送到iPhone。
第三阶段:iPhone把发来的消息传递给相应的应用程序,并且按照设定弹出Push通知。
从上图我们可以看到:
1、应用程序注册消息推送。
2、iOS从APNS Server获取device token,应用程序接收device token。
3、应用程序将device token发送给PUSH服务端程序。
4、服务端程序向APNS服务发送消息。
5、APNS服务将消息发送给iPhone应用程序。
无论是iPhone客户端和APNS,还是Provider和APNS,都需要通过证书进行连接。
二、消息推送的实现
下面我介绍一下几种用到的证书。
1、CSR文件<1>、生成Certificate Signing Request(CSR)
<2>、填写你的邮箱和常用名称,并选择保存到硬盘。
点击继续
这样就在本地生成了一个Push.certSigningRequest文件。
2、p12文件
<1>、导出密钥。
<2>、输入你的密码
这样就生成了一个Push.p12文件。
3、SSL certificate文件
<1>、新建一个App ID
在setting中勾选下面选项
并且点击下面,create Certificate 按钮,创建证书,结果如下
注意看enable变绿了,说明是可行的。
<2>、创建下载,并且命名为aps_developer_identity.cer。
那么,到现在为止,我们已经生成了三个文件:
1、Push.certSigningRequest
2、Push.p12
3、aps_developer_identity.cer
在项目的AppDelegate中的didFinishLaunchingWithOptions方法中加入下面的代码:
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeBadge)];
我们还需要通过下面的回调方法获取deviceToken
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { NSString *token = [NSString stringWithFormat:@"%@", deviceToken]; NSLog(@"My token is:%@", token); } - (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { NSString *error_str = [NSString stringWithFormat: @"%@", error]; NSLog(@"Failed to get token, error:%@", error_str); }
获取到的deviceToken,我们可以提交给后台应用程序,发送通知的后台应用程序除了需要知道deviceToken之外,还需要一个与APNS连接的证书。
这个证书可以通过我们前面生成的两个文件中得到。
在终端,用shell命令进行操作。
1、将aps_developer_identity.cer转换成aps_developer_identity.pem格式
openssl x509 -in aps_developer_identity.cer -inform DER -out aps_developer_identity.pem -outform PEM
2、将p12格式的私钥转换成pem
openssl pkcs12 -nocerts -out Push_Noenc.pem -in Push.p12
3、创建p12文件
openssl pkcs12 -export -in aps_developer_identity.pem -inkey Push_Noenc.pem -certfile Push.certSigningRequest -name "aps_developer_identity" -out aps_developer_identity.p12
这样我们就得到了在.net或java等后台应用程序中使用的证书文件:aps_developer_identity.p12
如果后台应用是php的话,那么可以按照 iOS消息推送机制中pem文件的生成这篇文章中的方法来生成php后台应用程序中使用的证书文件:ck.pem
参考:http://2015.iteye.com/blog/1337599