0

为我的应用获取下一个本地通知集的时间的最佳方法是什么?

我知道以下循环可用于获取通知,但这是否总是按时间顺序排序,以便我可以获取项目 [0] 的时间,还是按添加时间的顺序?怎么能从中拉出时间呢?我需要获取整个日期并格式化超时,还是有更好的方法?

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
}

非常感谢!

山姆

4

2 回答 2

6

这确实是两个问题。首先,如何获得下一个通知。其次,如何仅获取该通知日期的时间部分。

第一,按包含对象的日期属性对数组进行排序

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

二,只得到日期的小时和分钟

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]];
于 2013-07-14T19:02:06.050 回答
1

你不能保证scheduledLocalNotifications数组的顺序。如果您需要在应用程序中多次获取最新通知,我建议使用UIApplication包含for循环的方法创建实用程序类别。这样你就可以调用:

notif = [[UIApplication sharedApplication] nextLocalNotification];

不要重复自己。

于 2013-07-14T18:28:33.890 回答