ios如何实现推送通知
推送通知的步骤:1、询问是否允许推送通知。2、如果用户允许在APPDELEGATE 中实现
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken{
}
3、将token发送到服务器上
4、服务器收到toke后 发送推送通知,客户端相应该推送同通知
代码如下:
- //每次唤醒
- - (void)applicationDidBecomeActive:(UIApplication *)application
- {
- /*
- 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.
- */
- //每次醒来都需要去判断是否得到device token
- [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(registerForRemoteNotificationToGetToken) userInfo:nil repeats:NO];
- //hide the badge
- application.applicationIconBadgeNumber = 0;
- [[CheckVersion sharedCVInstance] checkVersionOfServer];
- [[AnalyticsUtil sharedAnalyticsUtil] appLaunch];
- AnalyticsJSONElement *viewElement = [[AnalyticsJSONElement alloc] init];
- viewElement.jsonType = AnalyticsJSONTypeView;
- viewElement.typeID = @"0";
- [[AnalyticsUtil sharedAnalyticsUtil] postAnalyticsMsgToServerWithElement:viewElement];
- [viewElement release];
- }
- - (void)applicationWillTerminate:(UIApplication *)application
- {
- /*
- Called when the application is about to terminate.
- Save data if appropriate.
- See also applicationDidEnterBackground:.
- */
- }
- #pragma mark -
- #pragma mark - Getting Device token for Notification support
- //向服务器申请发送token 判断事前有没有发送过
- - (void)registerForRemoteNotificationToGetToken
- {
- NSLog(@"Registering for push notifications...");
- //注册Device Token, 需要注册remote notification
- NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
- if (![userDefaults boolForKey:DeviceTokenRegisteredKEY]) //如果没有注册到令牌 则重新发送注册请求
- {
- dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
- [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
- (UIRemoteNotificationTypeNewsstandContentAvailability |
- UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge |
- UIRemoteNotificationTypeSound)];
- });
- }
- //将远程通知的数量置零
- dispatch_async(dispatch_get_global_queue(0,0), ^{
- //1 hide the local badge
- if ([[UIApplication sharedApplication] applicationIconBadgeNumber] == 0) {
- return;
- }
- // [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
- //2 ask the provider to set the BadgeNumber to zero
- NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
- NSString *deviceTokenStr = [userDefaults objectForKey:DeviceTokenStringKEY];
- [self resetBadgeNumberOnProviderWithDeviceToken:deviceTokenStr];
- });
- }
- //允许的话 自动回调的函数
- - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
- {
- //将device token转换为字符串
- NSString *deviceTokenStr = [NSString stringWithFormat:@"%@",deviceToken];
- //modify the token, remove the "<, >"
- NSLog(@" deviceTokenStr lentgh: %d ->%@", [deviceTokenStr length], [[deviceTokenStr substringWithRange:NSMakeRange(0, 72)] substringWithRange:NSMakeRange(1, 71)]);
- deviceTokenStr = [[deviceTokenStr substringWithRange:NSMakeRange(0, 72)] substringWithRange:NSMakeRange(1, 71)];
- NSLog(@"deviceTokenStr = %@",deviceTokenStr);
- //将deviceToken保存在NSUserDefaults
- NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
- //保存 device token 令牌,并且去掉空格
- [userDefaults setObject:[deviceTokenStr stringByReplacingOccurrencesOfString:@" " withString:@""] forKey:DeviceTokenStringKEY];
- //send deviceToken to the service provider
- dispatch_async(dispatch_get_global_queue(0,0), ^{
- //没有在service provider注册Device Token, 需要发送令牌到服务器
- if ( ![userDefaults boolForKey:DeviceTokenRegisteredKEY] )
- {
- NSLog(@" 没有 注册Device Token");
- [self sendProviderDeviceToken:deviceTokenStr];
- }
- });
- }
- - (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
- NSString *str = [NSString stringWithFormat: @"Error: %@", err];
- NSLog(@"获取令牌失败: %@",str);
- //如果device token获取失败则需要重新获取一次
- //[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(registerForRemoteNotificationToGetToken) userInfo:nil repeats:NO];
- }
- //获取远程通知
- - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
- NSLog(@"received badge number ---%@ ----",[[userInfo objectForKey:@"aps"] objectForKey:@"badge"]);
- for (id key in userInfo) {
- NSLog(@"key: %@, value: %@", key, [userInfo objectForKey:key]);
- }
- NSLog(@"the badge number is %d", [[UIApplication sharedApplication] applicationIconBadgeNumber]);
- NSLog(@"the application badge number is %d", application.applicationIconBadgeNumber);
- application.applicationIconBadgeNumber += 1;
- // We can determine whether an application is launched as a result of the user tapping the action
- // button or whether the notification was delivered to the already-running application by examining
- // the application state.
- //当用户打开程序时候收到远程通知后执行
- if (application.applicationState == UIApplicationStateActive) {
- // Nothing to do if applicationState is Inactive, the iOS already displayed an alert view.
- UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示"
- message:[NSString stringWithFormat:@"\n%@",
- [[userInfo objectForKey:@"aps"] objectForKey:@"alert"]]
- delegate:self
- cancelButtonTitle:@"OK"
- otherButtonTitles:nil];
- dispatch_async(dispatch_get_global_queue(0,0), ^{
- //hide the badge
- application.applicationIconBadgeNumber = 0;
- //ask the provider to set the BadgeNumber to zero
- NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
- NSString *deviceTokenStr = [userDefaults objectForKey:DeviceTokenStringKEY];
- [self resetBadgeNumberOnProviderWithDeviceToken:deviceTokenStr];
- });
- [alertView show];
- [alertView release];
- }
- }
- // http://192.168.11.24/ClientInterface.ashx?action= savetoken&clientid=3898329492492424924932&token=343424324242
- #pragma mark -
- #pragma mark - Getting Device token for Notification support
- //发送token
- - (void)sendProviderDeviceToken: (NSString *)deviceTokenString
- {
- // Establish the request
- NSLog(@"sendProviderDeviceToken = %@", deviceTokenString);
- NSString *UDIDString = [[UIDevice currentDevice] uniqueIdentifier];
- NSString *body = [NSString stringWithFormat:@"action=savetoken&clientid=%@&token=%@", UDIDString, deviceTokenString];
- NSString *baseurl = [NSString stringWithFormat:@"%@?",URL_OF_PUSH_NOTIFICATION_SERVER]; //服务器地址
- NSLog(@"send provider device token = %@", baseurl);
- NSURL *url = [NSURL URLWithString:baseurl];
- NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
- [urlRequest setHTTPMethod: @"POST"];
- [urlRequest setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
- [urlRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
- NSURLConnection *tConnection = [[NSURLConnection alloc] initWithRequest: urlRequest delegate: self];
- self.deviceTokenConnetion = [tConnection retain];
- [tConnection release];
- }
- #pragma mark -
- #pragma mark - reset Badge Number
- - (void)resetBadgeNumberOnProviderWithDeviceToken: (NSString *)deviceTokenString
- {
- NSLog(@" reset Provider DeviceToken %@", deviceTokenString);
- isNotificationSetBadge = YES;
- // Establish the request
- NSString *body = [NSString stringWithFormat:@"action=setbadge&token=%@", [deviceTokenString stringByReplacingOccurrencesOfString:@" " withString:@""]];
- NSString *baseurl = [NSString stringWithFormat:@"%@?", URL_OF_PUSH_NOTIFICATION_SERVER]; //服务器地址
- NSURL *url = [NSURL URLWithString:baseurl];
- NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
- [urlRequest setHTTPMethod: @"POST"];
- [urlRequest setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
- [urlRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
- NSURLConnection *tConnection = [[NSURLConnection alloc] initWithRequest: urlRequest delegate: self];
- self.deviceTokenConnetion = [tConnection retain];
- [tConnection release];
- }
- #pragma mark -
- #pragma mark - NSURLConnection delegate function
- - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
- {
- NSHTTPURLResponse *resp = (NSHTTPURLResponse *)response;
- NSLog(@"Response statusCode: %d", resp.statusCode);
- }
- - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
- {
- NSString *rsp = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
- NSLog(@"connection 2 Received data = %@ ", rsp);
- //if the string from provider is "true", means the devicetoken is stored in the provider server
- //so the app won't send the devicetoken next time.
- if (isNotificationSetBadge == NO) {
- NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
- if([rsp isEqualToString:@"true"])
- {
- NSLog(@"connection 2.2 Received data = %@ ", rsp);
- [userDefaults setBool:YES forKey:DeviceTokenRegisteredKEY];
- }
- }else{//isNotificationSetBadge == YES;
- NSLog(@"connection 2 reset");
- isNotificationSetBadge = NO;
- }
- [rsp release];
- }
- - (void)connectionDidFinishLoading:(NSURLConnection *)connection
- {
- NSLog(@"connection 3 Did Finish Loading ");
- [self.deviceTokenConnetion cancel];
- }
ios如何实现推送通知的更多相关文章
- iOS上简单推送通知(Push Notification)的实现
iOS上简单推送通知(Push Notification)的实现 根据这篇很好的教程(http://www.raywenderlich.com/3443/apple-push-notification ...
- 转:向IOS设备发送推送通知
背景 SMS 和 MMS 消息是由无线运营商通过设备的电话号码向特定设备提供的.实现 SMS/MMS 的服务器端应用程序的开发人员必须费大量精力才能与现有的封闭电信基础架构进行交互(其中包括获取电话号 ...
- iOS 玩转推送通知
转自:http://www.cocoachina.com/ios/20160316/15665.html 前言 推送通知,想必大家都很熟悉,关于原理之类的,这里就不过多阐述.在这里我们主要介绍下iOS ...
- 【读书笔记】iOS网络-使用推送通知
一,本地通知 本地通知有64位的最大限制.虽然,你依然可以调度通知,不过到到达的通知数被限定为接近64个,并且按照fireDate的顺序排序,系统会忽略掉其余的通知.这意味着如果现在有64个调用的本地 ...
- iOS 远程推送通知
1.什么是推送通知 在某些特殊情况下,应用程序被动收到的以不同种界面形式出现的提醒信息 推送通知的作用:可以让不在前台运行的app通知app发生了改变 iOS中得推送通知种类 远程推送通知(Remot ...
- 推送通知iOS客户端编写实现及推送服务器端编写
http://blog.csdn.net/tonny_guan/article/details/8963262 1.iOS客户端编程 推送通知技术在Mac OS X和iOS系统上都可以运行,我们本章主 ...
- IOS之推送通知(本地推送和远程推送)
推送通知和NSNotification是有区别的: NSNotification:是看不到的 推送通知:是可以看到的 IOS中提供了两种推送通知 本地推送通知:(Local Notification) ...
- iOS推送通知
推送通知 此通知非彼通知. NSNotification是抽象的,看不见的,但是可以监听,属于观察者模式的一种设计模式. 推送通知是可见的,能用肉眼看见的,是真正的和用户打交道的通知. 推送通知分为两 ...
- iOS推送通知的实现步骤
一.关于推送通知 来源:http://blog.csdn.net/enuola/article/details/8627283 推送通知,也被叫做远程通知,是在iOS 3.0以后被引入的功能.是当程序 ...
随机推荐
- Android自定义Activity酷炫的动画跳转效果
两个Activity跳转的时候,自定义翻页效果: Intent intent = new Intent(FirstActivity.this, SecondActivity.class); sta ...
- Response.Write具体介绍
问题一: Response.Write 后连接Response.Redirect ,则Response.Write无法显示,直接跳转入Response.Redirect 的页面. 解决方案: Resp ...
- Unity3d 要点板书
WWW.unity3d.com.cn Unity Project unity的项目文件/专案 Scene unity的场景文件 Scene 场景视窗 Game 预览视窗 H... 物件视窗 Pro ...
- sql server varchar(10)和 nvarchar(10)存储数据长度
) 存储10个字母,英文标点符号等,5个汉字以及中文标点等. )存储10汉字.字母等,不区分中英文.
- C# 颜色有3种表示方式: 6位16进制、RGB、 颜色关键字
最常用的是6位16进制的代码表示法.如bgcolor=#ff0000;其中#只是表示使用6位16进制的颜色代码声明颜色.代码的头两位即ff表示三原色中的红色,范围当然是16进制的00-ff,中间两位即 ...
- Oracle中如何判断字符串是否全为数字,以及从任意字符串中提取数字
本文介绍了判断字符串是否全为数字的4种办法,另外还介绍了一个translate函数的小技巧,从任意字符串中提取数字(调用2次translate函数).这个办法是一个公司同事发现的,用起来很方便,但理解 ...
- jquery.qrcode二维码插件生成彩色二维码
jquery.qrcode.js 是居于jquery类库的绘制二维码的插件,用它来实现二维码图形渲染支持canvas和table两种绘图方式. (jquery.qrcode.js 设置显示方式为tab ...
- ndk 编译 boost 库,支持serialization
Boost库是一个可移植.提供源代码的C++库,作为标准库的后备,是C++标准化进程的开发引擎之一. Boost库由C++标准委员会库工作组成员发起,其中有些内容有望成为下一代C++标准库内容.在C+ ...
- Linux 下修改Tomcat使用的JVM内存大小
我的服务器的配置: # OS specific support. $var _must_ be set to either true or false. JAVA_OPTS="-Xms10 ...
- Android 三大图片缓存原理、特性对比
这是我在 MDCC 上分享的内容(略微改动),也是源码解析第一期发布时介绍的源码解析后续会慢慢做的事. 从总体设计和原理上对几个图片缓存进行对比,没用到他们的朋友也可以了解他们在某些特性上的实现. 上 ...