您的位置:首页 > 移动开发 > IOS开发

iOS 推送通知的实现

2013-10-28 17:44 369 查看
消息推送:分为本地通知和远程通知,区别为:

本地通知由由应用程序计划,并同一设备上的iOS发出 ;
推送通知,又叫远程通知,由远程服务器上的程序(提供者)发至APNs,再由APNs把消息推送至设备上的某个程序。

有码有真相:

首先需要在APNS上注册推送服务

-(void)alertNotice:(NSString *)title withMSG:(NSString *)msg cancleButtonTitle:(NSString *)cancleTitle otherButtonTitle:(NSString *)otherTitle
{
UIAlertView *alert;
if([otherTitle isEqualToString:@""])
alert = [[UIAlertView alloc] initWithTitle:title message:msg delegate:self cancelButtonTitle:cancleTitle otherButtonTitles:nil,nil];
else
alert = [[UIAlertView alloc] initWithTitle:title message:msg delegate:self cancelButtonTitle:cancleTitle otherButtonTitles:otherTitle,nil];
[alert show];
[alert release];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

// Override point for customization after application launch.

// Add the view controller's view to the window and display.
[self.window addSubview:viewController.view];
[self.window makeKeyAndVisible];
[self alertNotice:@"" withMSG:@"Initiating Remote Noticationss Are Active" cancleButtonTitle:@"Ok" otherButtonTitle:@""];
//注册远程推送
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound)];

return YES;
}


接着,APNS就会返回一个唯一deviceToken

//注册远程通知成功,APNS将返回唯一标示的设备令牌码deviceToken

- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
//注册远程通知成功
//NSLog(@"devToken=%@",deviceToken);
NSString* strToken = [NSString stringWithFormat:@"devToken=%@",deviceToken];
NSLog(@"%@", strToken);
[self alertNotice:@"" withMSG:strToken cancleButtonTitle:@"Ok" otherButtonTitle:@""];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
NSDictionary *aps = [userInfo objectForKey:@"aps"];
//在应用Icon右上角显示推送通知的个数
if (aps && [aps isKindOfClass:[NSDictionary class]]) {
int badgeNumber = [[aps objectForKey:@"badge"] intValue];
if (badgeNumber > 0) {
[UIApplication sharedApplication].applicationIconBadgeNumber = badgeNumber;
}
}
}

- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err
{
//注册远程推送失败
NSLog(@"Error in registration. Error: %@", err);
[self alertNotice:@"" withMSG:[NSString stringWithFormat:@"Error in registration. Error: %@", err] cancleButtonTitle:@"Ok" otherButtonTitle:@""];
}


到现在iOS方面的编程已经完工,剩下的就是消息推送后台的设置了

首先,需要制作证书,证书的制作流程,推荐:http://docs.jpush.cn/pages/viewpage.action?pageId=1343727

PS:根据后台语言的不同,最后需要使用的证书文件也不同,Java后台需要使用的就是最后生成证书的秘钥,就是p12证书文件,.Net后台需要再进一步将证书文件生成一个pem文件。
参考文章:/article/1403512.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: