2011-08-25 65 views
2

我有本地通知的代碼,我有一個scheduleNotification和clearNotification使用我自己的方法。這些是代碼:取消特定的UILocalNotification

- (void)clearNotification { 
    [[UIApplication sharedApplication] cancelAllLocalNotifications]; 
} 

- (void)scheduleNotification { 
    [reminderText resignFirstResponder]; 
    [[UIApplication sharedApplication] cancelAllLocalNotifications]; 

    Class cls = NSClassFromString(@"UILocalNotification"); 
    if (cls != nil) { 
     UILocalNotification *notif = [[cls alloc] init]; 
     notif.fireDate = [[datePicker date] dateByAddingTimeInterval:-30]; 
     notif.timeZone = [NSTimeZone defaultTimeZone]; 

     notif.alertBody = @"Evaluation Planner"; 
     notif.alertAction = @"Details"; 
     notif.soundName = UILocalNotificationDefaultSoundName; 
     notif.applicationIconBadgeNumber = 1; 

    NSDictionary *userDict = [NSDictionary dictionaryWithObject:reminderText.text forKey:kRemindMeNotificationDataKey]; 
    notif.userInfo = userDict; 
    [[UIApplication sharedApplication] scheduleLocalNotification:notif]; 
    [notif release]; 
    } 
} 

這些代碼運行良好,但現在我想知道如何知道它將刪除哪個通知對象。我想爲通知創建一個ID,也就是說,一個ID相當於一個通知。但我不知道我應該在哪一部分做到這一點。另外,我需要找到一種方法將所有這些都包含在plist中。

希望有人能幫助我。謝謝。

回答

11
NSArray *notifications = [[UIApplication sharedApplication] scheduledLocalNotifications]; 
for (UILocalNotification *not in notifications) { 
    NSString *dateString=[not.userInfo valueForKey:@"EndDate"]; 
    if([dateString isEqualToString:@"CompareString"]) 
    { 
     [[UIApplication sharedApplication] cancelLocalNotification:not]; 
    } 
} 
  1. 給用戶的信息,只要你創建本地通知(這是一個鍵值對)。
  2. 遍歷通知(它包含所有本地通知)並比較已知密鑰的值。在上面的例子中,我使用EndDate作爲鍵,CompareString作爲值。

它的工作與我很好。

乾杯..

+0

只是想補充說,命名變量「不」會產生錯誤。 – OthmanT

2
(void)cancelLocalNotification:(NSString*)notificationID 
{ 

    // UILocalNotification *cancelThisNotification = nil; 
    // BOOL hasNotification = NO; 

    for (int j =0;j<[[[UIApplication sharedApplication]scheduledLocalNotifications]count]; j++) 
    { 
     UILocalNotification *someNotification = [[[UIApplication sharedApplication]scheduledLocalNotifications]objectAtIndex:j]; 
     if([[someNotification.userInfo objectForKey:@"drdid"] isEqualToString:notificationID]) 
     { 
      NSLog(@"id,notificationID(App) %@ %@ ",[someNotification.userInfo objectForKey:@"drdid"],notificationID); 
      NSLog(@"canceled notifications %@",someNotification); 
      [[UIApplication sharedApplication] cancelLocalNotification:someNotification]; 
     } 

    } 
} 
+0

userInfo是我一直在尋找的,謝謝! – Stephanie

0

我會建議使用上UILocalNotification用戶信息屬性,如其他人所說。一個簡單的實現,接受的答案是:

for(UILocalNotification* notification in [[UIApplication sharedApplication]scheduledLocalNotifications]) 
{ 
     if([[notification.userInfo objectForKey:@"notification_identifier"] isEqualToString:@"notification_001"]) 
     { 
      [[UIApplication sharedApplication] cancelLocalNotification:notification]; 
     } 
} 

這樣的循環要簡單得多。我不確定它是多少有點優化,但它肯定比較容易閱讀,我假設你只有幾個通知可以循環。