2013-07-14 42 views
0

獲取下一個本地通知集的時間的最佳方式是什麼?獲取下一個iOS本地通知的時間

我知道下面的循環可以用來獲取通知,但這是否總是按時間順序排序,所以我可以得到item [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 
} 

非常感謝!

山姆

回答

6

這實際上是兩個問題。首先,如何獲得下一個通知。其次,如何獲取通知日期的時間組件。

一把手,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]; 

二,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]]; 
+0

非常好的解決方案,謝謝 –

1

不能保證scheduledLocalNotifications排列的順序。如果您需要在應用程序中多次獲取最新通知,我建議使用包含for循環的方法在UIApplication上創建實用程序類別。這樣你就可以打電話:

notif = [[UIApplication sharedApplication] nextLocalNotification]; 

不要重複自己。

+0

我只需要一次。該代碼是我得到多少的樣本。我不確定如何專門找到下一個的時間。 – samiles