Search code examples
objective-cuitableviewios5xcode4uilocalnotification

Cancel local notification not working


I've spent half of my day reading all "How to cancel a local notification" questions and answers. After all, I came up with my own solution but apparently it is not working. I have a tableview with all my scheduled notifications....

on the H file I have

@property (strong, nonatomic) UILocalNotification *theNotification;

and then on the M file:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *notificationArray = [[UIApplication sharedApplication] scheduledLocalNotifications];
    theNotification = [notificationArray objectAtIndex:indexPath.row];
    NSLog(@"Notification to cancel: %@", [theNotification description]); 
    // NSLOG Perfectly describes the notification to be cancelled. But then It will give me      "unrecognized selector"


    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Local Reminder"
                                                    message:@"Cancel local reminder ?"
                                                   delegate:self
                                          cancelButtonTitle:@"No"
                                          otherButtonTitles:@"Yes", nil];
    [alertView show];
    [alertView release];    
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        NSLog(@"Cancel");
    }else{ 
        NSLog(@"Ok");
        [[UIApplication sharedApplication] cancelLocalNotification:theNotification];
    }
}

If I click "Ok" I get: 2012-02-04 03:34:48.806 Third test[8921:207] -[__NSCFType encodeWithCoder:]: unrecognized selector sent to instance 0x890ae90 Program received signal "SIGABRT".

If I can totally identify the notification to be cancelled why does it give me that ?


Solution

  • In my app I did it like this:

    - (IBAction)cancelLocalNotification:(id)sender 
    {
        for (UILocalNotification *lNotification in [[UIApplication sharedApplication] scheduledLocalNotifications]) 
        {
            if ([[lNotification.userInfo valueForKey:@"FlightUniqueIDKey"] isEqualToString:flightNo]) 
            {
                [[UIApplication sharedApplication] cancelLocalNotification:lNotification];
            }
        }
    }
    

    And when I scheduled local notification, I added a key. FlightNo is a unique ID for notification.

    NSDictionary *infoDict = [NSDictionary dictionaryWithObject:flightNo forKey:@"FlightUniqueIDKey"];
    
    localNotif.userInfo = infoDict;
    

    Note from Nick Farina: this works for scheduled notifications only; you can't seem to cancel a notification presented via presentLocalNotificationNow: