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

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

}

3、将token发送到服务器上

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

代码如下:

[cpp] view plaincopy

 
  1. //每次唤醒
[cpp] view plaincopy

 
  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. //每次醒来都需要去判断是否得到device token
  7. [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(registerForRemoteNotificationToGetToken) userInfo:nil repeats:NO];
  8. //hide the badge
  9. application.applicationIconBadgeNumber = 0;
  10. [[CheckVersion sharedCVInstance] checkVersionOfServer];
  11. [[AnalyticsUtil sharedAnalyticsUtil] appLaunch];
  12. AnalyticsJSONElement *viewElement = [[AnalyticsJSONElement alloc] init];
  13. viewElement.jsonType = AnalyticsJSONTypeView;
  14. viewElement.typeID = @"0";
  15. [[AnalyticsUtil sharedAnalyticsUtil] postAnalyticsMsgToServerWithElement:viewElement];
  16. [viewElement release];
  17. }
  18. - (void)applicationWillTerminate:(UIApplication *)application
  19. {
  20. /*
  21. Called when the application is about to terminate.
  22. Save data if appropriate.
  23. See also applicationDidEnterBackground:.
  24. */
  25. }
  26. #pragma mark -
  27. #pragma mark - Getting Device token for Notification support
  28. //向服务器申请发送token 判断事前有没有发送过
  29. - (void)registerForRemoteNotificationToGetToken
  30. {
  31. NSLog(@"Registering for push notifications...");
  32. //注册Device Token, 需要注册remote notification
  33. NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
  34. if (![userDefaults boolForKey:DeviceTokenRegisteredKEY])   //如果没有注册到令牌 则重新发送注册请求
  35. {
  36. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  37. [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
  38. (UIRemoteNotificationTypeNewsstandContentAvailability |
  39. UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge |
  40. UIRemoteNotificationTypeSound)];
  41. });
  42. }
  43. //将远程通知的数量置零
  44. dispatch_async(dispatch_get_global_queue(0,0), ^{
  45. //1 hide the local badge
  46. if ([[UIApplication sharedApplication] applicationIconBadgeNumber] == 0) {
  47. return;
  48. }
  49. // [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
  50. //2 ask the provider to set the BadgeNumber to zero
  51. NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
  52. NSString *deviceTokenStr = [userDefaults objectForKey:DeviceTokenStringKEY];
  53. [self resetBadgeNumberOnProviderWithDeviceToken:deviceTokenStr];
  54. });
  55. }
  56. //允许的话 自动回调的函数
  57. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
  58. {
  59. //将device token转换为字符串
  60. NSString *deviceTokenStr = [NSString stringWithFormat:@"%@",deviceToken];
  61. //modify the token, remove the  "<, >"
  62. NSLog(@"    deviceTokenStr  lentgh:  %d  ->%@", [deviceTokenStr length], [[deviceTokenStr substringWithRange:NSMakeRange(0, 72)] substringWithRange:NSMakeRange(1, 71)]);
  63. deviceTokenStr = [[deviceTokenStr substringWithRange:NSMakeRange(0, 72)] substringWithRange:NSMakeRange(1, 71)];
  64. NSLog(@"deviceTokenStr = %@",deviceTokenStr);
  65. //将deviceToken保存在NSUserDefaults
  66. NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
  67. //保存 device token 令牌,并且去掉空格
  68. [userDefaults setObject:[deviceTokenStr stringByReplacingOccurrencesOfString:@" " withString:@""] forKey:DeviceTokenStringKEY];
  69. //send deviceToken to the service provider
  70. dispatch_async(dispatch_get_global_queue(0,0), ^{
  71. //没有在service provider注册Device Token, 需要发送令牌到服务器
  72. if ( ![userDefaults boolForKey:DeviceTokenRegisteredKEY] )
  73. {
  74. NSLog(@" 没有 注册Device Token");
  75. [self sendProviderDeviceToken:deviceTokenStr];
  76. }
  77. });
  78. }
  79. - (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
  80. NSString *str = [NSString stringWithFormat: @"Error: %@", err];
  81. NSLog(@"获取令牌失败:  %@",str);
  82. //如果device token获取失败则需要重新获取一次
  83. //[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(registerForRemoteNotificationToGetToken) userInfo:nil repeats:NO];
  84. }
  85. //获取远程通知
  86. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
  87. NSLog(@"received badge number ---%@ ----",[[userInfo objectForKey:@"aps"] objectForKey:@"badge"]);
  88. for (id key in userInfo) {
  89. NSLog(@"key: %@, value: %@", key, [userInfo objectForKey:key]);
  90. }
  91. NSLog(@"the badge number is  %d",  [[UIApplication sharedApplication] applicationIconBadgeNumber]);
  92. NSLog(@"the application  badge number is  %d",  application.applicationIconBadgeNumber);
  93. application.applicationIconBadgeNumber += 1;
  94. // We can determine whether an application is launched as a result of the user tapping the action
  95. // button or whether the notification was delivered to the already-running application by examining
  96. // the application state.
  97. //当用户打开程序时候收到远程通知后执行
  98. if (application.applicationState == UIApplicationStateActive) {
  99. // Nothing to do if applicationState is Inactive, the iOS already displayed an alert view.
  100. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示"
  101. message:[NSString stringWithFormat:@"\n%@",
  102. [[userInfo objectForKey:@"aps"] objectForKey:@"alert"]]
  103. delegate:self
  104. cancelButtonTitle:@"OK"
  105. otherButtonTitles:nil];
  106. dispatch_async(dispatch_get_global_queue(0,0), ^{
  107. //hide the badge
  108. application.applicationIconBadgeNumber = 0;
  109. //ask the provider to set the BadgeNumber to zero
  110. NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
  111. NSString *deviceTokenStr = [userDefaults objectForKey:DeviceTokenStringKEY];
  112. [self resetBadgeNumberOnProviderWithDeviceToken:deviceTokenStr];
  113. });
  114. [alertView show];
  115. [alertView release];
  116. }
  117. }
  118. // http://192.168.11.24/ClientInterface.ashx?action= savetoken&clientid=3898329492492424924932&token=343424324242
  119. #pragma mark -
  120. #pragma mark - Getting Device token for Notification support
[cpp] view plaincopy

 
  1. //发送token
  2. - (void)sendProviderDeviceToken: (NSString *)deviceTokenString
  3. {
  4. // Establish the request
  5. NSLog(@"sendProviderDeviceToken = %@", deviceTokenString);
  6. NSString *UDIDString = [[UIDevice currentDevice] uniqueIdentifier];
  7. NSString *body = [NSString stringWithFormat:@"action=savetoken&clientid=%@&token=%@", UDIDString, deviceTokenString];
  8. NSString *baseurl = [NSString stringWithFormat:@"%@?",URL_OF_PUSH_NOTIFICATION_SERVER];  //服务器地址
  9. NSLog(@"send provider device token = %@", baseurl);
  10. NSURL *url = [NSURL URLWithString:baseurl];
  11. NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
  12. [urlRequest setHTTPMethod: @"POST"];
  13. [urlRequest setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
  14. [urlRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
  15. NSURLConnection *tConnection = [[NSURLConnection alloc] initWithRequest: urlRequest delegate: self];
  16. self.deviceTokenConnetion = [tConnection retain];
  17. [tConnection release];
  18. }
  19. #pragma mark -
  20. #pragma mark - reset Badge Number
  21. - (void)resetBadgeNumberOnProviderWithDeviceToken: (NSString *)deviceTokenString
  22. {
  23. NSLog(@"  reset Provider DeviceToken %@", deviceTokenString);
  24. isNotificationSetBadge = YES;
  25. // Establish the request
  26. NSString *body = [NSString stringWithFormat:@"action=setbadge&token=%@", [deviceTokenString stringByReplacingOccurrencesOfString:@" " withString:@""]];
  27. NSString *baseurl = [NSString stringWithFormat:@"%@?", URL_OF_PUSH_NOTIFICATION_SERVER];  //服务器地址
  28. NSURL *url = [NSURL URLWithString:baseurl];
  29. NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
  30. [urlRequest setHTTPMethod: @"POST"];
  31. [urlRequest setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
  32. [urlRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
  33. NSURLConnection *tConnection = [[NSURLConnection alloc] initWithRequest: urlRequest delegate: self];
  34. self.deviceTokenConnetion = [tConnection retain];
  35. [tConnection release];
  36. }
  37. #pragma mark -
  38. #pragma mark - NSURLConnection delegate function
  39. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
  40. {
  41. NSHTTPURLResponse *resp = (NSHTTPURLResponse *)response;
  42. NSLog(@"Response statusCode:    %d", resp.statusCode);
  43. }
  44. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
  45. {
  46. NSString *rsp = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  47. NSLog(@"connection    2  Received data = %@  ", rsp);
  48. //if the string from provider is "true", means the devicetoken is stored in the provider server
  49. //so the app won't send the devicetoken next time.
  50. if (isNotificationSetBadge == NO) {
  51. NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
  52. if([rsp isEqualToString:@"true"])
  53. {
  54. NSLog(@"connection    2.2  Received data = %@  ", rsp);
  55. [userDefaults setBool:YES forKey:DeviceTokenRegisteredKEY];
  56. }
  57. }else{//isNotificationSetBadge == YES;
  58. NSLog(@"connection    2  reset");
  59. isNotificationSetBadge = NO;
  60. }
  61. [rsp release];
  62. }
  63. - (void)connectionDidFinishLoading:(NSURLConnection *)connection
  64. {
  65. NSLog(@"connection    3  Did Finish Loading ");
  66. [self.deviceTokenConnetion cancel];
  67. }

ios如何实现推送通知的更多相关文章

  1. iOS上简单推送通知(Push Notification)的实现

    iOS上简单推送通知(Push Notification)的实现 根据这篇很好的教程(http://www.raywenderlich.com/3443/apple-push-notification ...

  2. 转:向IOS设备发送推送通知

    背景 SMS 和 MMS 消息是由无线运营商通过设备的电话号码向特定设备提供的.实现 SMS/MMS 的服务器端应用程序的开发人员必须费大量精力才能与现有的封闭电信基础架构进行交互(其中包括获取电话号 ...

  3. iOS 玩转推送通知

    转自:http://www.cocoachina.com/ios/20160316/15665.html 前言 推送通知,想必大家都很熟悉,关于原理之类的,这里就不过多阐述.在这里我们主要介绍下iOS ...

  4. 【读书笔记】iOS网络-使用推送通知

    一,本地通知 本地通知有64位的最大限制.虽然,你依然可以调度通知,不过到到达的通知数被限定为接近64个,并且按照fireDate的顺序排序,系统会忽略掉其余的通知.这意味着如果现在有64个调用的本地 ...

  5. iOS 远程推送通知

    1.什么是推送通知 在某些特殊情况下,应用程序被动收到的以不同种界面形式出现的提醒信息 推送通知的作用:可以让不在前台运行的app通知app发生了改变 iOS中得推送通知种类 远程推送通知(Remot ...

  6. 推送通知iOS客户端编写实现及推送服务器端编写

    http://blog.csdn.net/tonny_guan/article/details/8963262 1.iOS客户端编程 推送通知技术在Mac OS X和iOS系统上都可以运行,我们本章主 ...

  7. IOS之推送通知(本地推送和远程推送)

    推送通知和NSNotification是有区别的: NSNotification:是看不到的 推送通知:是可以看到的 IOS中提供了两种推送通知 本地推送通知:(Local Notification) ...

  8. iOS推送通知

    推送通知 此通知非彼通知. NSNotification是抽象的,看不见的,但是可以监听,属于观察者模式的一种设计模式. 推送通知是可见的,能用肉眼看见的,是真正的和用户打交道的通知. 推送通知分为两 ...

  9. iOS推送通知的实现步骤

    一.关于推送通知 来源:http://blog.csdn.net/enuola/article/details/8627283 推送通知,也被叫做远程通知,是在iOS 3.0以后被引入的功能.是当程序 ...

随机推荐

  1. ThreadPool.QueueUserWorkItem的性能问题

    在WEB开发中,为了降低页面等待时间提高用户体验,我们往往会把一些浪费时间的操作放到新线程中在后台执行. 简单的实现代码就是: //代码一 new Thread(()=>{ //do somet ...

  2. js高程笔记--创建对象

    1.工厂模式 ex: function createPerson( name, age, job) { var o = new Object() ; o.name = name; o.job = jo ...

  3. 【译】html5游戏入门

    [译]html5游戏入门 原文链接 简介 如果你想用canvas做个游戏,那么来对地方了. 但是但是你至少知道javascript怎么拼写(╯‵□′)╯︵┻━┻ 既然没问题,那先来玩一下或者下载 创建 ...

  4. JavaScript知识(二)

    你要保守你心,胜过保守一切,因为一生的果效,是由心发出的.————O(∩_∩)O... ...O(∩_∩)O...老师因有事下午没来上课,今天就只把中午讲的知识总结一下.由于昨天只是讲了JavaScr ...

  5. 转 --maven系列之一 简介

    http://blog.csdn.net/jiuqiyuliang/article/details/41076215 [项目管理和构建]——Maven简介(一) 2015-01-31 21:27 68 ...

  6. Linux学习之Makefile文件的编写

    转自:http://goodcandle.cnblogs.com/archive/2006/03/30/278702.html 目的:       基本掌握了 make 的用法,能在Linux系统上编 ...

  7. 《JavaScript+DOM编程艺术》的摘要(四)appendChild与insertBefore的区别

    基本知识点: // 1.js里面为什么要添加window.onload=function (){} // 保证html文档都加载完了,才开始运行js代码,以防html文档没有加载完,找不到相应的元素 ...

  8. PhpStorm 10.0 激活方式

    随着 JetBrains 新版本的发布,注册机已然不行了.然而,道高一尺,魔高一丈.IntelliJ IDEA开源社区 提供了如下通用激活方法:注册时选择License server填写http:// ...

  9. Oracle字符集转换

            这几天在工作中碰到一个字符乱码的问题,发现在cmd窗口的sqlplus中直接update一个中文和使用@调用一个文件作同样更新的时候,存储的结果 竟不一样.一时比较迷惑,对Oracle ...

  10. stl 迭代子的失效

    迭代子是STL中很重要的特性,但是其很脆弱(我个人认为),因为使用它的条件很苛刻,一不小心就失效了.其在两中情况下可能会失效. 1.当容器有插入操作时 在初始化了迭代子后,如果容器有插入操作时,迭代子 ...