iOS 推送通知的實現

消息推送:分爲本地通知和遠程通知,區別爲:

  • 本地通知由由應用程序計劃,並同一設備上的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文件。
參考文章:http://blog.csdn.net/kmyhy/article/details/6792855


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章