2012-02-04 33 views
7

He pasado la mitad de mi día leyendo todas las preguntas y respuestas sobre "Cómo cancelar una notificación local". Después de todo, se me ocurrió mi propia solución, pero aparentemente no funciona. Tengo un tableview con todas mis notificaciones programadas ....Cancelar notificación local no funciona

en el archivo H tengo

@property (strong, nonatomic) UILocalNotification *theNotification; 

y luego en el archivo M:

- (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]; 
    } 
} 

Si hago clic en "Ok "Obtengo: 2012-02-04 03: 34: 48.806 Tercera prueba [8921: 207] - [__ NSCFType encodeWithCoder:]: selector no reconocido enviado a la instancia 0x890ae90 Programa recibido señal" SIGABRT ".

Si puedo identificar por completo la notificación que se cancelará ¿por qué me da eso?

Respuesta

12

En mi aplicación lo hice así:

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

Y cuando me programado notificación locales, añadí una tecla. FlightNo es una identificación única para la notificación.

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

localNotif.userInfo = infoDict; 

Nota de Nick Farina: esto funciona para sólo las notificaciones programadas; parece que no puede cancelar una notificación presentada a través de presentLocalNotificationNow:

+2

Estaba tratando de encontrar una manera en la que 1 - No es necesario descartar el controlador 2 - Visualice la notificación que se elimina 3 - No tiene que configurar una clave específica cada vez. Su respuesta es totalmente válida, solo tuve que trabajar un poco más para obtener un mejor resultado visual. Gracias por tu respuesta. Aceptaré y votaré. – Farini

+2

Tenga en cuenta que esto funciona para las notificaciones _scheduled_ solamente; parece que no puede cancelar una notificación presentada a través de 'presentLocalNotificationNow:'. ¡Solo me llevó un año descubrirlo! –

+0

@Farini no dude en editar mi respuesta para que sea mejor :) – Shmidt

3

Encontré una manera de que pueda hacer que se vea un poco mejor. Si desea eliminar localNotification directamente de la tabla, puede agregar un botón "cancelar" o "eliminar" a cada celda. de este modo:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
static NSString *CellIdentifier = @"Cell"; 

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
if (cell == nil) { 
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 
} 
NSArray *notificationArray = [[UIApplication sharedApplication] scheduledLocalNotifications]; 
UILocalNotification *notif = [notificationArray objectAtIndex:indexPath.row]; 
[cell.textLabel setText:notif.alertBody]; 

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
[dateFormat setDateFormat:@"MM/ d/ YYYY"]; 
NSString *dateOnRecord = [dateFormat stringFromDate:notif.fireDate]; 

[cell.detailTextLabel setText:dateOnRecord]; 

UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
cancelButton.frame = CGRectMake(200, 5, 80, 34); 
[cancelButton setTitle:@"Cancel" forState:UIControlStateNormal]; 

cancelButton.titleLabel.textColor = [UIColor redColor]; 
cancelButton.backgroundColor = [UIColor colorWithRed:0.5 green:0.0 blue:0.0 alpha:1.0]; 
[cancelButton setTag:indexPath.row]; 
[cancelButton addTarget:self action:@selector(cancelNotification:) forControlEvents:UIControlEventTouchUpInside]; 
[cell.contentView addSubview:cancelButton]; 
[dateFormat release]; 
return cell; 
} 

Y entonces el código del teléfono botón:

-(void)cancelNotification:(id)sender { 
NSArray *notificationArray = [[UIApplication sharedApplication] scheduledLocalNotifications]; 
UILocalNotification *notif = [notificationArray objectAtIndex:[sender tag]]; 
[[UIApplication sharedApplication] cancelLocalNotification:notif]; 
[self.tableView reloadData]; 
} 

Eso es sólo otra manera de hacerlo. Me parece un poco mejor para visualizar.

Cuestiones relacionadas