博客> iOS开发---本地消息推送
iOS开发---本地消息推送
2019-10-20 03:56 评论:0 阅读:1232 nanawu
ios 本地推送 本地 推送间隔出错

Action!go! 第一步:要进行本地推送,首先要有推送啊,所以让我们先来注册一个推送通知吧! 可以在Appdelegate.m中的第一个方法中注册,也可以自定义通知初始化的地方 //创建一个本地通知对象 UILocalNotification locNoti = [[UILocalNotification alloc]init]; //对该本地通知对象的属性进行赋值 1、 //设置触发的时间 NSDate fireDate = [NSDate dateWithTimeIntervalSinceNow:10]; locNoti.fireDate = fireDate; 2、//设置时区 locNoti.timeZone = [NSTimeZone defaultTimeZone]; 3、//设置重复的间隔 locNoti.repeatInterval = kCFCalendarUnitMinute; 4、 //通知内容
locNoti.alertBody = @"加油啊!"; locNoti.applicationIconBadgeNumber = 1; 5、 //通知被触发时播放的声音 locNoti.soundName = UILocalNotificationDefaultSoundName; 6、//通知的参数 NSDictionary *dict = [NSDictionary dictionaryWithObject:@"好好学习,天天向上" forKey:@"key"]; locNoti.userInfo = dict; 7、判断当前设备系统的版本 iOS8之前和iOS8之后是不一样的 if ([[[UIDevice currentDevice]systemVersion]floatValue]<8.0) { [[UIApplication sharedApplication]registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert)]; locNoti.repeatInterval = NSCalendarUnitHour; }else{ [[UIApplication sharedApplication]registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert) categories:nil]]; locNoti.repeatInterval = NSCalendarUnitHour; } //执行注册通知 [[UIApplication sharedApplication]scheduleLocalNotification:locNoti];

通知触发之后会调用 // 本地通知回调函数,当应用程序在前台时调用 -(void)application:(UIApplication )application didReceiveLocalNotification:(nonnull UILocalNotification )notification{ NSLog(@"%@",notification); NSString notiMess = [notification.userInfo objectForKey:@"key"]; UIAlertView alert = [[UIAlertView alloc]initWithTitle:@"本地通知(前台)" message:notiMess delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; //更新右上方小红点个数 NSInteger badge = [[UIApplication sharedApplication]applicationIconBadgeNumber]; badge--; badge = badge >= 0 ? badge : 0; [UIApplication sharedApplication].applicationIconBadgeNumber = badge; //在不需要推送的时候,可以取消 [HomeViewController cancelNotificationWithKey:@"key"];

}

//取消某个本地通知 +(void)cancelNotificationWithKey:(NSString )key{ //获取所有本地通知 NSArray NotiArray = [UIApplication sharedApplication].scheduledLocalNotifications; for (UILocalNotification localNoti in NotiArray){ NSDictionary dict = localNoti.userInfo; if (dict) { NSLog(@"****%@",dict); // 根据设置通知参数时指定的key来获取通知参数 NSString *info = dict[key]; // 如果找到需要取消的通知,则取消 if (info != nil) { [[UIApplication sharedApplication]cancelLocalNotification:localNoti]; break; } } } }

收藏
0
sina weixin mail 回到顶部