最近开发过程中涉及到了推送功能,下面将详细的步骤总结一下,以方便大家!
有必要先来了解一下推送的工作原理!
可以简单的用下图来概括:
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,都需要通过证书进行连接。
一、CSR文件
1、生成Certificate Signing Request(CSR)
3、可以看到钥匙串访问界面发生了变化,多出了两个密钥
二、p12文件
1、选择专用密钥,右击,导出密钥。
2、输入你的密码。
这样就生成了一个Push.p12文件,这里提醒一下,要记住这个密码,后面要用到。
三、SSL certificate文件
1.新建一个App ID,刚建完,push是关闭的,需点击后边的configurable
2、点击Continue按钮
3、选择刚才创建的CSR证书,点击Generate按钮,稍等片刻,会显示Download按钮,下载此证书并安装(aps_developer_identity.cer)
4、安装完成后,钥匙串访问中会多出一项Apple Development IOS Push Services:*******
二、准备profile证书,因为推送消息只能再真机上测试,所以要建一个profile证书
进入后新建一个Provisioning Profiles
接下来是选择账号、设备,完成之后,下载
切记把之前xcode中的Provisioning Profiles删除掉
然后再安装
三、接下来进入程序中设置一下
1.更改应用的Bundle identifier 为刚新建的App ID中的ID(切记)
2.修改Target中的Build Setting---Code Signing中的两项为刚刚新建的那个(push)。
3.在didFinishLaunchingWithOptions 中加入一下代码
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self.window makeKeyAndVisible]; [[UIApplication sharedApplication] registerForRemoteNotificationTypes: UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert];
return YES;
}
注册成功后打印token
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)pToken {
NSLog(@"regisger success:%@", pToken);
//注册成功,将deviceToken保存到应用服务器数据库中
}
接到消息后处理- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
// 处理推送消息
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"通知" message:@"我的信息" delegate:selfcancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
[alert show];
[alert release];
NSLog(@"%@", userInfo);
}
注册失败,打印错误信息- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(@"Regist fail%@",error);
}
到这里一切顺利的话我们就可以在真机(切记)运行了,注册成功我们会得到iphone 的deviceToken若已获取到token,则继续往下
四、在应用服务器采用php的方式将消息推送给APNS,
1、php连接APNS也是需要证书的,还记得我们上面获得的几个证书吗?打开终端,对上面的证书做如下处理,
cd 进入证书所在目录
把.cer文件转换成.pem文件:
$ openssl x509 -in aps_developer_identity.cer -inform der -out PushChatCert.pem
把私钥Push.p12文件转换成.pem文件:
$ openssl pkcs12 -nocerts -out PushChatKey.pem -in Push.p12
Enter Import Password:(之前生成.p12文件时设置的密码)
MAC verified OK
Enter PEM pass phrase:(随便设置)
Verifying – Enter PEM pass phrase:(再来一次,与上边一致)
你首先需要为.p12文件输入passphrase密码短语,这样OpenSSL可以读它。然后你需要键入一个新的密码短语来加密PEM文件。还是使用”pushchat”来作为PEM的密码短语。你需要选择一些更安全的密码短语。
注意:如果你没有键入一个PEM passphrase,OpenSSL将不会返回一个错误信息,但是产生的.pem文件里面将不会含有私钥。
最后。把私钥和证书整合到一个.pem文件里:
$ cat PushChatCert.pem PushChatKey.pem > ck.pem
把下边的php脚本复制后,保存到文本中,改扩展名为push.php
<?php // Put your device token here (without spaces): $deviceToken = '你的设备token'; // Put your private key's passphrase here: $passphrase = '刚刚设置的,没忘记吧'; // Put your alert message here: $message = 'My first push test!'; //////////////////////////////////////////////////////////////////////////////// $ctx = stream_context_create(); stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem'); stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase); // Open a connection to the APNS server $fp = stream_socket_client( 'ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx); if (!$fp) exit("Failed to connect: $err $errstr" . PHP_EOL); echo 'Connected to APNS' . PHP_EOL; // Create the payload body $body['aps'] = array( 'alert' => $message, 'sound' => 'default' ); // Encode the payload as JSON $payload = json_encode($body); // Build the binary notification $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload; // Send it to the server $result = fwrite($fp, $msg, strlen($msg)); if (!$result) echo 'Message not delivered' . PHP_EOL; else echo 'Message successfully delivered' . PHP_EOL; // Close the connection to the server fclose($fp); ?>
进入此目录,输入命令php push.php
若显示:
Connected to APNS
Message successfully delivered
则表示推送成功!
要想设备接收到推送,需把设备上的app关闭,等待一会儿就可以接收到了!
over!!!