- (void)scheduleLocalNotification {
// 初始化本地通知
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
// 通知触发时间
localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:3];
// 触发后,弹出警告框中显示的内容
localNotification.alertBody = @"弹出警告框中显示的内容";
// 触发时的声音(这里选择的系统默认声音)
localNotification.soundName = UILocalNotificationDefaultSoundName;
// 触发频率(repeatInterval是一个枚举值,可以选择每分、每小时、每天、每年等)
localNotification.repeatInterval = NSCalendarUnitDay;
// 需要在App icon上显示的未读通知数(设置为1时,多个通知未读,系统会自动加1,如果不需要显示未读数,这里可以设置0)
localNotification.applicationIconBadgeNumber = 1;
// 设置通知的id,可用于通知移除,也可以传递其他值,当通知触发时可以获取
localNotification.userInfo = @{@"id" : @"notificationId1"};
// 注册本地通知
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
当本地通知触发后,需要在AppDelegate中进行接收并做相应处理。在AppDelegate中,实现以下方法:
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:notification.alertBody delegate:nil cancelButtonTitle:@"确认" otherButtonTitles:nil];
[alert show];
}
[[UIApplication sharedApplication] cancelAllLocalNotifications];
一种是按照id来移除,这个id就是在注册通知时,写的id:
- (void)removeLocalNotification {
// 取出全部本地通知
NSArray *notifications = [UIApplication sharedApplication].scheduledLocalNotifications;
// 设置要移除的通知id
NSString *notificationId = @"notificationId1";
// 遍历进行移除
for (UILocalNotification *localNotification in notifications) {
// 将每个通知的id取出来进行对比
if ([[localNotification.userInfo objectForKey:@"id"] isEqualToString:notificationId]) {
// 移除某一个通知
[[UIApplication sharedApplication] cancelLocalNotification:localNotification];
}
}
}
注意事项
1. 如果需要做一个闹钟或备忘录之类的应用,则将时间作为fireDate,触发之后可以进行移除;
2. 一个App中,本地通知数量最多64个,不用的通知要及时移除;
3. 如果通知的时间是后台返回的,那每次需要将通知全部移除,再添加新的。