现在的位置: 首页 > 综合 > 正文

IOS 如何实现推送通知

2018年05月06日 ⁄ 综合 ⁄ 共 10761字 ⁄ 字号 评论关闭

//  http://blog.csdn.net/ios_che/article/details/7428413

推送通知的步骤:1、询问是否允许推送通知。2、如果用户允许在APPDELEGATE 中实现

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{

}

3、将token发送到服务器上

4、服务器收到toke后 发送推送通知,客户端相应该推送同通知

代码如下:

  1. //每次唤醒  
  1. - (void)applicationDidBecomeActive:(UIApplication *)application  
  2. {  
  3.     /* 
  4.      Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. 
  5.      */  
  6.       
  7.     //每次醒来都需要去判断是否得到device token  
  8.     [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(registerForRemoteNotificationToGetToken) userInfo:nil repeats:NO];  
  9.     //hide the badge  
  10.     application.applicationIconBadgeNumber = 0;  
  11.   
  12.     [[CheckVersion sharedCVInstance] checkVersionOfServer];  
  13.       
  14.     [[AnalyticsUtil sharedAnalyticsUtil] appLaunch];  
  15.       
  16.     AnalyticsJSONElement *viewElement = [[AnalyticsJSONElement alloc] init];  
  17.     viewElement.jsonType = AnalyticsJSONTypeView;  
  18.     viewElement.typeID = @"0";  
  19.     [[AnalyticsUtil sharedAnalyticsUtil] postAnalyticsMsgToServerWithElement:viewElement];  
  20.     [viewElement release];  
  21.   
  22.       
  23. }  
  24.   
  25. - (void)applicationWillTerminate:(UIApplication *)application  
  26. {  
  27.     /* 
  28.      Called when the application is about to terminate. 
  29.      Save data if appropriate. 
  30.      See also applicationDidEnterBackground:. 
  31.      */  
  32. }  
  33.   
  34.   
  35. #pragma mark -  
  36. #pragma mark - Getting Device token for Notification support  
  37. //向服务器申请发送token 判断事前有没有发送过  
  38. - (void)registerForRemoteNotificationToGetToken  
  39. {  
  40.     NSLog(@"Registering for push notifications...");  
  41.       
  42.     //注册Device Token, 需要注册remote notification  
  43.     NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];  
  44.       
  45.       
  46.     if (![userDefaults boolForKey:DeviceTokenRegisteredKEY])   //如果没有注册到令牌 则重新发送注册请求  
  47.     {  
  48.         dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{  
  49.               
  50.             [[UIApplication sharedApplication] registerForRemoteNotificationTypes:  
  51.              (UIRemoteNotificationTypeNewsstandContentAvailability |   
  52.               UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge |  
  53.               UIRemoteNotificationTypeSound)];  
  54.         });  
  55.     }  
  56.       
  57.     //将远程通知的数量置零  
  58.     dispatch_async(dispatch_get_global_queue(0,0), ^{  
  59.         //1 hide the local badge  
  60.         if ([[UIApplication sharedApplication] applicationIconBadgeNumber] == 0) {  
  61.             return;  
  62.         }  
  63.         // [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];  
  64.           
  65.         //2 ask the provider to set the BadgeNumber to zero  
  66.         NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];  
  67.         NSString *deviceTokenStr = [userDefaults objectForKey:DeviceTokenStringKEY];  
  68.         [self resetBadgeNumberOnProviderWithDeviceToken:deviceTokenStr];  
  69.     });  
  70.       
  71. }  
  72.   
  73. //允许的话 自动回调的函数  
  74. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken  
  75. {  
  76.       
  77.     //将device token转换为字符串  
  78.     NSString *deviceTokenStr = [NSString stringWithFormat:@"%@",deviceToken];  
  79.       
  80.       
  81.     //modify the token, remove the  "<, >"  
  82.     NSLog(@"    deviceTokenStr  lentgh:  %d  ->%@", [deviceTokenStr length], [[deviceTokenStr substringWithRange:NSMakeRange(0, 72)] substringWithRange:NSMakeRange(1, 71)]);  
  83.     deviceTokenStr = [[deviceTokenStr substringWithRange:NSMakeRange(0, 72)] substringWithRange:NSMakeRange(1, 71)];  
  84.       
  85.     NSLog(@"deviceTokenStr = %@",deviceTokenStr);  
  86.       
  87.       
  88.     //将deviceToken保存在NSUserDefaults  
  89.       
  90.     NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];  
  91.     //保存 device token 令牌,并且去掉空格  
  92.     [userDefaults setObject:[deviceTokenStr stringByReplacingOccurrencesOfString:@" " withString:@""] forKey:DeviceTokenStringKEY];        
  93.       
  94.       
  95.       
  96.       
  97.     //send deviceToken to the service provider  
  98.       
  99.     dispatch_async(dispatch_get_global_queue(0,0), ^{  
  100.           
  101.         //没有在service provider注册Device Token, 需要发送令牌到服务器  
  102.         if ( ![userDefaults boolForKey:DeviceTokenRegisteredKEY] )  
  103.         {  
  104.             NSLog(@" 没有 注册Device Token");  
  105.             [self sendProviderDeviceToken:deviceTokenStr];  
  106.         }  
  107.     });  
  108.       
  109.       
  110. }  
  111.   
  112. - (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {   
  113.       
  114.     NSString *str = [NSString stringWithFormat: @"Error: %@", err];  
  115.     NSLog(@"获取令牌失败:  %@",str);  
  116.       
  117.     //如果device token获取失败则需要重新获取一次  
  118.     //[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(registerForRemoteNotificationToGetToken) userInfo:nil repeats:NO];  
  119. }  
  120.   
  121.   
  122.   
  123. //获取远程通知  
  124.   
  125. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {  
  126.       
  127.     NSLog(@"received badge number ---%@ ----",[[userInfo objectForKey:@"aps"] objectForKey:@"badge"]);  
  128.       
  129.     for (id key in userInfo) {  
  130.         NSLog(@"key: %@, value: %@", key, [userInfo objectForKey:key]);  
  131.     }      
  132.       
  133.     NSLog(@"the badge number is  %d",  [[UIApplication sharedApplication] applicationIconBadgeNumber]);  
  134.     NSLog(@"the application  badge number is  %d",  application.applicationIconBadgeNumber);  
  135.     application.applicationIconBadgeNumber += 1;  
  136.       
  137.   
  138.     // We can determine whether an application is launched as a result of the user tapping the action  
  139.     // button or whether the notification was delivered to the already-running application by examining  
  140.     // the application state.  
  141.       
  142.     //当用户打开程序时候收到远程通知后执行  
  143.     if (application.applicationState == UIApplicationStateActive) {  
  144.         // Nothing to do if applicationState is Inactive, the iOS already displayed an alert view.  
  145.         UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示"  
  146.                                                             message:[NSString stringWithFormat:@"\n%@",  
  147.                                                                      [[userInfo objectForKey:@"aps"] objectForKey:@"alert"]]  
  148.                                                            delegate:self  
  149.                                                   cancelButtonTitle:@"OK"  
  150.                                                   otherButtonTitles:nil];  
  151.           
  152.         dispatch_async(dispatch_get_global_queue(0,0), ^{  
  153.             //hide the badge  
  154.             application.applicationIconBadgeNumber = 0;  
  155.               
  156.             //ask the provider to set the BadgeNumber to zero  
  157.             NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];  
  158.             NSString *deviceTokenStr = [userDefaults objectForKey:DeviceTokenStringKEY];  
  159.             [self resetBadgeNumberOnProviderWithDeviceToken:deviceTokenStr];  
  160.         });  
  161.           
  162.         [alertView show];  
  163.         [alertView release];  
  164.           
  165.     }  
  166.       
  167.       
  168. }  
  169.   
  170.   
  171.   
  172. // http://192.168.11.24/ClientInterface.ashx?action= savetoken&clientid=3898329492492424924932&token=343424324242  
  173.   
  174. #pragma mark -  
  175. #pragma mark - Getting Device token for Notification support  
  1. //发送token  
  2. - (void)sendProviderDeviceToken: (NSString *)deviceTokenString  
  3. {  
  4.   
  5.     // Establish the request  
  6.     NSLog(@"sendProviderDeviceToken = %@", deviceTokenString);  
  7.       
  8.     NSString *UDIDString = [[UIDevice currentDevice] uniqueIdentifier];  
  9.     NSString *body = [NSString stringWithFormat:@"action=savetoken&clientid=%@&token=%@", UDIDString, deviceTokenString];  
  10.       
  11.     NSString *baseurl = [NSString stringWithFormat:@"%@?",URL_OF_PUSH_NOTIFICATION_SERVER];  //服务器地址  
  12.       
  13.     NSLog(@"send provider device token = %@", baseurl);  
  14.       
  15.     NSURL *url = [NSURL URLWithString:baseurl];  
  16.     NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];  
  17.       
  18.     [urlRequest setHTTPMethod: @"POST"];  
  19.     [urlRequest setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];  
  20.     [urlRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];  
  21.       
  22.     NSURLConnection *tConnection = [[NSURLConnection alloc] initWithRequest: urlRequest delegate: self];  
  23.     self.deviceTokenConnetion = [tConnection retain];  
  24.     [tConnection release];  
  25. }  
  26.   
  27. #pragma mark -  
  28. #pragma mark - reset Badge Number  
  29.   
  30. - (void)resetBadgeNumberOnProviderWithDeviceToken: (NSString *)deviceTokenString  
  31. {  
  32.     NSLog(@"  reset Provider DeviceToken %@", deviceTokenString);  
  33.     isNotificationSetBadge = YES;  
  34.       
  35.     // Establish the request  
  36.     NSString *body = [NSString stringWithFormat:@"action=setbadge&token=%@", [deviceTokenString stringByReplacingOccurrencesOfString:@" " withString:@""]];  
  37.       
  38.     NSString *baseurl = [NSString stringWithFormat:@"%@?", URL_OF_PUSH_NOTIFICATION_SERVER];  //服务器地址  
  39.     NSURL *url = [NSURL URLWithString:baseurl];  
  40.     NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];  
  41.       
  42.     [urlRequest setHTTPMethod: @"POST"];  
  43.     [urlRequest setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];  
  44.     [urlRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];  
  45.       
  46.     NSURLConnection *tConnection = [[NSURLConnection alloc] initWithRequest: urlRequest delegate: self];  
  47.     self.deviceTokenConnetion = [tConnection retain];  
  48.     [tConnection release];  
  49. }  
  50.   
  51. #pragma mark -  
  52. #pragma mark - NSURLConnection delegate function  
  53.   
  54.   
  55. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response  
  56. {  
  57.     NSHTTPURLResponse *resp = (NSHTTPURLResponse *)response;  
  58.     NSLog(@"Response statusCode:    %d", resp.statusCode);  
  59. }  
  60.   
  61. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data  
  62. {  
  63.     NSString *rsp = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];  
  64.     NSLog(@"connection    2  Received data = %@  ", rsp);  
  65.       
  66.       
  67.       
  68.     //if the string from provider is "true", means the devicetoken is stored in the provider server  
  69.     //so the app won't send the devicetoken next time.  
  70.     if (isNotificationSetBadge == NO) {  
  71.           
  72.         NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];  
  73.         if([rsp isEqualToString:@"true"])  
  74.         {  
  75.             NSLog(@"connection    2.2  Received data = %@  ", rsp);  
  76.             [userDefaults setBool:YES forKey:DeviceTokenRegisteredKEY];       
  77.         }  
  78.           
  79.     }else{//isNotificationSetBadge == YES;  
  80.         NSLog(@"connection    2  reset");  
  81.         isNotificationSetBadge = NO;  
  82.     }  
  83.       
  84.     [rsp release];  
  85. }  
  86.   
  87. - (void)connectionDidFinishLoading:(NSURLConnection *)connection  
  88. {  
  89.     NSLog(@"connection    3  Did Finish Loading ");  
  90.     [self.deviceTokenConnetion cancel];  
  91. }     

抱歉!评论已关闭.