取消特定的UILocalNotification

时间:2011-08-25 06:57:09

标签: iphone objective-c ios notifications

我有本地通知的代码,我有一个scheduleNotification和clearNotification使用我自己的方法。这些是代码:

- (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中。

希望有人可以帮助我。感谢。

3 个答案:

答案 0 :(得分:12)

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作为值。
  3. 与我合作。

    干杯..

答案 1 :(得分: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];
        }

    }
}

答案 2 :(得分:0)

我建议在UILocalNotification上使用userInfo属性,正如其他人所提到的那样。一个更简单的实现,接受的答案是:

for(UILocalNotification* notification in [[UIApplication sharedApplication]scheduledLocalNotifications])
{
       if([[notification.userInfo objectForKey:@"notification_identifier"] isEqualToString:@"notification_001"])
       {
            [[UIApplication sharedApplication] cancelLocalNotification:notification];
       }
}
像这样的for循环要简单得多。我不确定它是否或多或少是最优的,但它肯定更容易阅读,我认为你只有一些通知可以循环播放。