本文作者为CocoaChina会员“marshluca”,帖子地址 http://www.cocoachina.com/bbs/read.php?tid-20723.html
1. 将app注册notification里面, 并从APNS上获取测试机的deviceToken.
1 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 2 [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)]; 3 // other codes here. 4 return YES; 5 } 6 7 - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { 8 NSLog(@"deviceToken: %@", deviceToken); 9 } 10 11 - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { 12 NSLog(@"Error in registration. Error: %@", error); 13 } 14 15 - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo 16 { 17 18 NSLog(@" 收到推送消息 : %@",[[userInfo objectForKey:@"aps"] objectForKey:@"alert"]); 19 if ([[userInfo objectForKey:@"aps"] objectForKey:@"alert"]!=NULL) { 20 UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"推送通知" 21 message:[[userInfo objectForKey:@"aps"] objectForKey:@"alert"] 22 delegate:self 23 cancelButtonTitle:@" 关闭" 24 otherButtonTitles:@" 更新状态",nil]; 25 [alert show]; 26 [alert release]; 27 } 28 } |
启动程序,将app注册到通知项后,在console里面找到打印的deviceToken:
|
2. 生成app在服务端需要的许可证
1)进入Provisioning Portal, 下载Certificates在development下的证书。
2) 找到需要测试的app id,然后enable它在development下的Apple Push Notification service: Development Push SSL Certificate。需要输入1)中的签名证书才可以生成一个aps_developer_identity.cer.
3) 双击aps_developer_identity.cer,会打开系统的key chain. 在My certificates下找到Apple Development Push Services。需要为certificate和它之下的private key各自export出一个.p12文件。(会出现设置密码过程)
4)需要将上面的2个.p12文件转成.pem格式:
|
|
5)如果需要对 key不进行加密:
|
6)然后就可以 合并两个.pem文件, 这个ck.pem就是服务端需要的证书了。
|
3. 服务端push通知到ANPS. 在cocoachina找到了两种方法:
1)php驱动。需要将ck.pem和php脚本放到server 上。全部的php代码是:
|
请 求一次 http://127.0.0.1/apns/apns.php?message=A%20test%20message%20from%20localhost&badge=2&sound=received5.caf就 会向APNS进行一次推送。我的请求结果如下:
|
2)pushMeBaby 驱动。将aps_developer_identity.cer导入到project里面,改名为apns.cer。