我正在尝试同时安排许多UILocalNotification
个。我刷新了大量数据,需要取消之前的所有通知并重新创建它们。目前我有这个代码来取消和创建通知:
- (void)scheduleNotifications {
NSDate *start = [NSDate date];
// Cancel old notifications
[NotificationHandler cancelNotificationsNamed:@"ScheduleNotification"];
if (self.user.scheduleNotifications.boolValue) {
for (NSInteger i = 0; i < self.user.scheduleDays.count; i++) {
ScheduleDay *day = [self.user.scheduleDays objectAtIndex:i];
for (SchedulePeriod *period in day.periods) {
if (period.desc.length > 0) {
NSDateComponents *dateComponents = [[NSCalendar autoupdatingCurrentCalendar] components:NSCalendarUnitDay|NSCalendarUnitWeekday|NSCalendarUnitMonth|NSCalendarUnitYear fromDate:[NSDate date]];
dateComponents.day += 2 + i - dateComponents.weekday;
NSArray *timeComponents = [period.startTime componentsSeparatedByString:@":"];
NSInteger hour = [[timeComponents objectAtIndex:0] integerValue];
dateComponents.hour = hour < 7 ? hour + 12 : hour; // add 12 to hour if before 7 (assume afternoon)
dateComponents.minute = [[timeComponents objectAtIndex:1] integerValue] - 5;
NSDate *fireDate = [[NSCalendar autoupdatingCurrentCalendar] dateFromComponents:dateComponents];
if ([[NSDate date] compare:fireDate] == NSOrderedDescending) {
fireDate = [fireDate dateByAddingTimeInterval:604800]; // add a week if date is passed
}
[NotificationHandler scheduleNotificationNamed:@"ScheduleNotification"
forDate:fireDate
message:period.desc
repeatWeekly:YES];
}
}
}
}
NSLog(@"%f sec", [[NSDate date] timeIntervalSinceDate:start]);
}
NotificationHandler.m:
+ (void)scheduleNotificationNamed:(NSString *)name forDate:(NSDate *)date message:(NSString *)message repeatWeekly:(BOOL)repeatWeekly {
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.userInfo = @{@"kNotificationName" : name};
notification.fireDate = date;
notification.alertBody = message;
notification.timeZone = [NSTimeZone defaultTimeZone];
if (repeatWeekly) {
notification.repeatInterval = NSCalendarUnitWeekOfYear;
}
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
+ (void)cancelNotificationsNamed:(NSString *)name {
for (UILocalNotification *notification in [[UIApplication sharedApplication] scheduledLocalNotifications]) {
if ([[[notification userInfo] objectForKey:@"kNotificationName"] isEqualToString:name]) {
[[UIApplication sharedApplication] cancelLocalNotification:notification];
}
}
}
不幸的是,有时需要几秒钟才能取消并创建阻止UI的通知。还有更好的方法吗?