Cancel UILocalNotification

f0rz picture f0rz · Jul 1, 2010 · Viewed 39.5k times · Source

I have a problem with my UILocalNotification.

I am scheduling the notification with my method.

- (void) sendNewNoteLocalReminder:(NSDate *)date  alrt:(NSString *)title
{
    // some code ...
    UILocalNotification *localNotif = [[UILocalNotification alloc] init]; 

    if (localNotif == nil)  
        return;

    localNotif.fireDate = itemDate; 
    localNotif.timeZone = [NSTimeZone defaultTimeZone];
    localNotif.alertAction = NSLocalizedString(@"View Details", nil); 
    localNotif.alertBody = title;
    localNotif.soundName = UILocalNotificationDefaultSoundName; 
    localNotif.applicationIconBadgeNumber = 0;

    NSDictionary *infoDict = [NSDictionary dictionaryWithObject:stringID forKey:@"id"]; 
    localNotif.userInfo = infoDict; 

    [[UIApplication sharedApplication] scheduleLocalNotification:localNotif]; 
    [localNotif release];
}

Its work fine and I'm correctly receiving the notification. The problem is when I should cancel the notification. Im using this method.

- (void) deleteNewNoteLocalReminder:(NSString*) reminderID noteIDe:(NSInteger)noteIDE
{
    [[UIApplication sharedApplication] cancelLocalNotification:(UILocalNotification *)notification ????  
}

Im not sure what to do here, but my questions are:

How do I know which UILocalNotification object I should delete?
Is there a way to list all notifications?

The only thing I have is the ID of which reminder I should delete.
I was thinking about to save the UILocalNotification object in my "Note" object and get it that way, and when I saving to my SQLite database serialize the object and so on ... is there a smarter way?

Answer

viggio24 picture viggio24 · Feb 2, 2011

My solution is to use the UILocalNotification userInfo dictionary. In fact what I do is to generate a unique ID for each of my notifications (of course this ID is something I'm able to retrieve later), then when I want to cancel the notification associated to a given ID I will simply scan all available notifications using the array:

[[UIApplication sharedApplication] scheduledLocalNotifications]

and then I try to match the notifications by investigating the ID. E.g.:


NSString *myIDToCancel = @"some_id_to_cancel";
UILocalNotification *notificationToCancel=nil;
for(UILocalNotification *aNotif in [[UIApplication sharedApplication] scheduledLocalNotifications]) {
  if([[aNotif.userInfo objectForKey:@"ID"] isEqualToString:myIDToCancel]) {
     notificationToCancel=aNotif;
     break;
  }
}
if(notificationToCancel) [[UIApplication sharedApplication] cancelLocalNotification:notificationToCancel];

I don't know if this approach is better or not with respect to the Archiving/Unarchving one, however it works and limits data to be saved to just an ID.

Edit: there was a missing braket