iPhone消息推送服务实现

一、开通“Apple Push Notification service”

1.进入 Provisioning Protal

2.选择App IDs

3.选择要开通“Apple Push Notification service”的AppID,点击“Configure”链接

4.点击“Enable for Apple Push Notification service”复选框

5.点击“Configure”按钮,选择CSR文件上传

6.点击“Download”按钮,下载CER文件,双击导入。

7.选择“Provisioning”,重新生成Provisioning Profile,下载,导入到XCode。(很重要)

 

二、生成PHP端推送消息到Apple服务器时需要的证书文件

1.选定推送服务证书(Apple Development Push Services*),导出到桌面,保存为Certificates.p12。

2.在终端中运行如下命令:

openssl pkcs12 -clcerts -nokeys -out cert.pem -in Certificates.p12 openssl pkcs12 -nocerts -out key.pem -in Certificates.p12 openssl rsa -in key.pem -out key.unencrypted.pem cat cert.pem key.unencrypted.pem > ck.pem

ck.pem文件则是PHP推送消息时所使用的证书文件。

三、iPhone中获取DeviceToken代码

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound)]; } - (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err { [self alertNotice:@"" withMSG:[NSString stringWithFormat:@"Error in registration. Error: %@", err] cancleButtonTitle:@"Ok" otherButtonTitle:@""]; } - (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { NSLog(@"devToken=%@",deviceToken); [self alertNotice:@"" withMSG:[NSString stringWithFormat:@"devToken=%@",deviceToken] cancleButtonTitle:@"Ok" otherButtonTitle:@""]; }

四、项目设置

Targets > $APP_NAME > context menu > Properties > Identifier
    修改 identifier 为App ID

五、PHP端推送消息代码

array("alert" => 'message', "badge" => 1, "sound" => 'received5.caf')); $ctx = stream_context_create(); stream_context_set_option($ctx, "ssl", "local_cert", "ck.pem"); $fp = stream_socket_client("ssl://gateway.sandbox.push.apple.com:2195", $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx); if (!$fp) { print "Failed to connect $err $errstrn"; return; } print "Connection OK/n"; $payload = json_encode($body); $msg = chr(0) . pack("n",32) . pack("H*", $deviceToken) . pack("n",strlen($payload)) . $payload; print "sending message :" . $payload . "/n"; fwrite($fp, $msg); fclose($fp); ?> 

六、注意事项

1.DeviceToken要去掉-

2.发布版本使用“gateway.push.apple.com”

 

你可能感兴趣的:(iPhone消息推送服务实现)