iPhone上关于Push Notify的实现

来源:互联网 发布:mac dns劫持怎么解决 编辑:程序博客网 时间:2024/05/21 07:07
Push是一个非常有用的功能。
要完成Push 的功能主要分三步:
1.准备好具有Push功能的证书。这一步浪费了一些时间,我用Sarfir居然没有反应后来用Firefox通过的。注意这里的证书不能是通配符的。
2.创建一个工程实现PUSH的相关功能。
a.注册

[[UIApplication sharedApplication]registerForRemoteNotific
ationTypes:(UIRemoteNotificationTypeBadge |
  UIRemoteNotificationTypeSound |UIRemoteNotificationTypeAlert)];

b.取deviceToken

//注册push服务
- (void)application:(UIApplication *) applicationdidRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSString*token = [[deviceToken description]stringByTrimmingCharactersInSet:
    [NSCharacterSetcharacterSetWithCharactersInString:@"<>"]];//去掉"<>"
    token =[[token description] stringByReplacingOccurrencesOfString:@" "withString:@""];//去掉中间空格
   NSLog(@"deviceToken: %@", token);
}

//注册push服务失败
- (void)application:(UIApplication *)applicationdidFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
   NSLog(@"Error in registration for APNS. Error: %@", error);
}


c.实现捕获到消息后的一些操作

//接收到push消息
- (void)application:(UIApplication *)applicationdidReceiveRemoteNotification:(NSDictionary *)userInfo {
   NSLog(@"收到推送消息 : %@",[[userInfo objectForKey:@"aps"]objectForKey:@"alert"]);
    UIAlertView*alert = [[UIAlertView alloc] initWithTitle:@"推送通知"
                                                   message:[[userInfo objectForKey:@"aps"]objectForKey:@"alert"]
                                                  delegate:self
                                         cancelButtonTitle:@"关闭"
                                         otherButtonTitles:@"更新状态",nil];
    [alertshow];
    [alertrelease];
}


d.注消操作
[[UIApplication sharedApplication]unregisterForRemoteNotifications];



3.实现服务端和Apns Server的通信
呵呵相当的麻烦啊,不过有个开源的PushMeBaby工程,将在1步生成的证书,导入到PushMeBaby的工程里,运行工程就可以实现效果了。让我们来happy下

http://s2.sinaimg.cn/orignal/5ccfd2d5gbabba1ec5481&690