samiles samiles - 5 months ago 22
Objective-C Question

Get time only of next iOS local notification

What is the best way to get the time of the next local notification set for my app?

I know the following loop can be used to get notifications, but does this always sort in time order so I could just get time of item [0], or is it in order of when they were added? And how can just time be pulled from this? Will I need to get whole date and format the time out, or is there a better way?

UIApplication *app = [UIApplication sharedApplication];
NSArray *eventArray = [app scheduledLocalNotifications];
for (int i=0; i<[eventArray count]; i++)
UILocalNotification* oneEvent = [eventArray objectAtIndex:i];
//oneEvent is a local notification
//get time of first one

Many thanks!



This is really two problems. First, how to get the next notification. Second, how to get just the time components of that notification's date.

Number one, sorting an array by a date property of the contained objects

NSSortDescriptor * fireDateDesc = [NSSortDescriptor sortDescriptorWithKey:@"fireDate" ascending:YES];
NSArray * notifications = [[UIApplication sharedApplication] scheduledLocalNotifications] sortedArrayUsingDescriptors:@[fireDateDesc]]
UILocalNotification * nextNote =  [notifications objectAtIndex:0];

Two, get just the hours and minutes from the date

NSDateComponents * comps = [[NSCalendar currentCalendar] components:(NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit) 
                                                           fromDate:[notification fireDate]];
// Now you have [comps hour]; [comps minute]; [comps second];

// Or if you just need a string, use NSDateFormatter:
NSDateFormatter * formatter = [NSDateFormatter new];
[formatter setDateFormat:@"HH:mm:ss"];
NSString * timeForDisplay = [formatter stringFromDate:[notification fireDate]];