本地通知:
本地通知是由本地应用触发的,它是基于时间行为的一种通知形式,例如闹钟定时、待办事项提醒,又或者一个应用在一段时候后不使用通常会提示用户使用此应用等都是本地通知
由于在iOS8之后,本地通知的写法有所改变,所以在此之前需要进行版本判断,如下:
- (BOOL)application:(UIApplication *)applicationdidFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
UIUserNotificationSettings *settings= [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge |UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
}
return YES;
}
一、添加本地推送
1、创建UILocalNotification (创建本地通知,注册)
2、设置处理通知的时间fireDate(触发通知的时间)
3、配置通知的内容:通知主体、、通知声音、图标、数字等
4、配置通知传递的自定义参数useInfo(可选)
5、调用通知,可以使用scheduleLocalNotification:按计划调度一个通知,也可以用presentLocalNotificationNow立即调用通知;
//创建本地通知对象
UILocalNotification *localNotification= [[UILocalNotificationalloc] init];
//设定调度时间,即通知五秒后执行
NSDate *nowDate = [NSDate date];
[localNotification setFireDate:[nowDate dateByAddingTimeInterval:5]];
//循环次数,kCFCalendarUnitWeekday一周一次
localNotification.repeatInterval=0;
//当前日历,使用前最好设置时区等信息以便能够自动同步时间
//notification.repeatCalendar=[NSCalendar currentCalendar];
//设定时区
[localNotification setTimeZone:[NSTimeZone defaultTimeZone]];
//设置弹出消息
[localNotification setAlertBody:@"抢购时间到了"];
[localNotification setAlertAction:@"show now"];
//设置通知声音
[localNotification setSoundName:UILocalNotificationDefaultSoundName];
//设置用户信息
localNotification .userInfo=@{@"id":@1,@"user":@"KenshinCui"};//绑定到通知上的其他附加信息
//设置IconbadgeNumber图标数字,设置count为全局变量用count来控制图标数字的增加
count++;
[localNotification setApplicationIconBadgeNumber:count];
//应用程序计划执行通知
[[UIApplicationsharedApplication]scheduleLocalNotification:localNotification];
[[[UIAlertViewalloc]initWithTitle:@"提示"message:@"设置提醒成功"delegate:nilcancelButtonTitle:@"OK"otherButtonTitles:nil,nil] show]
二、程序运行时接收到本地推送信息
-(void)application:(UIApplication *)applicationdidReceiveLocalNotification:(UILocalNotification *)notification{
//这里,你就可以通过notification的useinfo,干一些你想做的事情了
//这里是创建一个KViewController并在点击通知时切换到该页面
UIStoryboard *storyboard = [UIStoryboardstoryboardWithName:@"Main"bundle:nil];
KViewController *kViewController =[storyboard instantiateViewControllerWithIdentifier:@"KViewController"];
UINavigationController *navigationController= (UINavigationController *)self.window.rootViewController;
[navigationControllerpushViewController:kViewController animated:YES];
//图标数字在每次点开通知后都会减一,知道图标为0(即图标消失)不再减
application.applicationIconBadgeNumber-=1;
}
三、移除本地推送
#pragma mark移除本地通知
-(void)removeNotification{
[[UIApplicationsharedApplication] cancelAllLocalNotifications];
}