检测下一个将触发的UILocalNotification
有没有办法find下一个本地通知将触发NSDate
?
例如,我已经设置了三个本地通知:
通知#1:设定在昨天下午3:00开始,每天重复间隔。
通知#2:今天下午5:00开始,每天重复。
通知#3:明天下午6:00,每天重复播放。
鉴于目前是下午4:00,下一个将触发的本地通知是通知#2。
我如何检索本地通知并获取date?
我知道我可以在数组中检索这些本地通知,但是如何根据今天的date获取将会触发的下一个通知?
您的任务的主要目标是确定每个通知给定date后的“下一个启动date”。 UILocalNotification
的NSLog()
输出显示了下一个启动date,但不幸的是它似乎不能作为(公共)属性使用。
我已经从https://stackoverflow.com/a/18730449/1187415 (有小的改进)的代码,并重写为UILocalNotification
类别的方法。 (这并不完美,不包括时区已经分配给通知的情况。)
@interface UILocalNotification (MyNextFireDate) - (NSDate *)myNextFireDateAfterDate:(NSDate *)afterDate; @end @implementation UILocalNotification (MyNextFireDate) - (NSDate *)myNextFireDateAfterDate:(NSDate *)afterDate { // Check if fire date is in the future: if ([self.fireDate compare:afterDate] == NSOrderedDescending) return self.fireDate; // The notification can have its own calendar, but the default is the current calendar: NSCalendar *cal = self.repeatCalendar; if (cal == nil) cal = [NSCalendar currentCalendar]; // Number of repeat intervals between fire date and the reference date: NSDateComponents *difference = [cal components:self.repeatInterval fromDate:self.fireDate toDate:afterDate options:0]; // Add this number of repeat intervals to the initial fire date: NSDate *nextFireDate = [cal dateByAddingComponents:difference toDate:self.fireDate options:0]; // If necessary, add one more: if ([nextFireDate compare:afterDate] == NSOrderedAscending) { switch (self.repeatInterval) { case NSDayCalendarUnit: difference.day++; break; case NSHourCalendarUnit: difference.hour++; break; // ... add cases for other repeat intervals ... default: break; } nextFireDate = [cal dateByAddingComponents:difference toDate:self.fireDate options:0]; } return nextFireDate; } @end
使用它,您可以根据下一个启动date对本地通知数组进行sorting:
NSArray *notifications = @[notif1, notif2, notif3]; NSDate *now = [NSDate date]; NSArray *sorted = [notifications sortedArrayUsingComparator:^NSComparisonResult(UILocalNotification *obj1, UILocalNotification *obj2) { NSDate *next1 = [obj1 myNextFireDateAfterDate:now]; NSDate *next2 = [obj2 myNextFireDateAfterDate:now]; return [next1 compare:next2]; }];
现在sorted[0]
将成为下一个触发的通知。