//添加一个本地推送
-(void)addLocalNotification{
UILocalNotification *localNotification=[[UILocalNotification alloc]init];
//设置时区,如果设置为nil的话,那么UILocalNotification将在一段时候后被激发,而不是某一个确切时间被激发
localNotification.timeZone=[NSTimeZone defaultTimeZone];
//设置UILocalNotification的激发的确切时间,我这里设置的是5秒后激发,
localNotification.fireDate=[[NSDate date]dateByAddingTimeInterval:5];
//设置UILocalNotification的通知音,可以用系统默认,也可以使用自己的
localNotification.soundName=UILocalNotificationDefaultSoundName;
//设置UILocalNotification的内容
localNotification.alertBody=@"Hello World!";
//设置应用图标右上角的提示圆圈
localNotification.applicationIconBadgeNumber=1;
//设置UILocalNotification按钮的文本
localNotification.alertAction=@"Open";
//设置UILocalNotification传递的数据
NSDictionary *infoDic= [NSDictionary dictionaryWithObject:@"name" forKey:@"key"];
localNotification.userInfo = infoDic;
//设置重复的间隔,我这里设置的是间隔是每周
localNotification.repeatInterval=kCFCalendarUnitWeek;
//添加推送到UILocalNotification
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
//取消所有注册的本地推送消息
-(void)cancelAllLocalNotifications{
[[UIApplication sharedApplication] cancelAllLocalNotifications];
}
//取消指定本地推送消息
-(void)cancelLocalNotification:(UILocalNotification *)localNotification{
[[UIApplication sharedApplication]cancelLocalNotification:localNotification];
}
我在写Demo的时候遇到一个问题,逻辑是这样的:
应用进入后台,注册推送消息,应用被激活,运行在前台我就取消推送。
问题:注册一条消息,却会推送多条
原因:为了节省测试时间,我将UILocalNotification的fireDate设置成了5秒后激发,时间太短,系统还没来得及取消推送,就已经发出去了。
cancelAllLocalNotifications 失效点击打开链接
UILocalNotification:点击打开链接