iOS消息推送的工作机制可以简单的用下图来概括:
Provider是指某个iPhone软件的Push服务器,APNS是Apple Push Notification Service的缩写,是苹果的服务器。
上图可以分为三个阶段:
第三阶段:iPhone把发来的消息传递给相应的应用程序,并且按照设定弹出Push通知。
从上图我们可以看到:
1、应用程序注册消息推送。
2、iOS从APNS Server获取device token,应用程序接收device token。
3、应用程序将device token发送给PUSH服务端程序。
4、服务端程序向APNS服务发送消息。
5、APNS服务将消息发送给iPhone应用程序。
步骤一、
创建需要的证书 & 使用PHP编写服务器端推送代码
2. 创建一个 App ID ,如: com.tadpole.TestAPNs 注意:通配符 ID 不能用于推送通知服务。
3. 点击Apple ID旁的“Configure”,根据“向导” 的步骤生成一个签名上传,然后下载生成的许可证。
4. 双击.cer文件将你的 aps_development.cer 导入Keychain中。
5. 在Mac上打开“钥匙串访问”,然后在“登录”中选择 “密钥”分类,找到我们创建的证书,然后右击“Apple Development IOS Push Services: com.tadpole.TestAPNs” > 导出 “Apple Development IOS Push Services: com.tadpole.TestAPNs”。保存为 cert.p12 文件。
6. 通过终端命令将这个cert.p12文件转换为PEM格式,打开终端,cd 进入证书所在目录,执行如下命令:
$ openssl pkcs12 -in cert.p12 -out apple_push_notification_production.pem -nodes -clcerts
1.注册设备需要在app delegate的[application:didFinishLaunchingWithOptions:]方法中调用[application registerForRemoteNotificationTypes:]方法,代码如下:
– (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Register for push notifications
[application registerForRemoteNotificationTypes:
UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeSound];
returnYES;
}
– (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)pToken {
NSLog(@”regisger success:%@”, pToken);
//注册成功,将deviceToken保存到应用服务器数据库中,因为在写向ios推送信息的服务器端程序时要用到这个
}
– (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
// 处理推送消息
NSLog(@”userInfo == %@”,userInfo);
NSString *message = [[userInfo objectForKey:@”aps”]objectForKey:@”alert”];
UIAlertView *createUserResponseAlert = [[UIAlertViewalloc] initWithTitle:@”提示”
message: message
delegate:self
cancelButtonTitle:@”取消”
otherButtonTitles: @”确认”,
nil];
[createUserResponseAlert show];
}
– (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(@”Regist fail%@”,error);
}
到这里一切顺利的话我们就可以在真机运行了,注册成功我们会得到iphone 的deviceToken