The main goal of your task is to determine the "next fire date" after a given date for each notification. NSLog() output of UILocalNotification shows the next fire date, but unfortunately it does not seem to be available as a (public) property.
I took the code fooobar.com/questions/1330260 / ... (with slight improvements) and rewrote this as a category method for UILocalNotification . (This is not ideal. It does not apply to the case when the time zone is designated for notification.)
@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
Using this, you can sort the local notification array according to the following fire date:
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]; }];
Now sorted[0] will be the next notification that fires.
source share