Отмена локального уведомления не работает - PullRequest
7 голосов
/ 04 февраля 2012

Я провел половину своего дня, читая все вопросы и ответы «Как отменить локальное уведомление». В конце концов, я придумал собственное решение, но, видимо, оно не работает. У меня есть таблица со всеми запланированными уведомлениями ....

в файле H у меня есть

@property (strong, nonatomic) UILocalNotification *theNotification;

и затем в файле 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];
    }
}

Если я нажму "ОК", я получу: 2012-02-04 03: 34: 48.806 Третий тест [8921: 207] - [__NSCFType encodeWithCoder:]: нераспознанный селектор, отправленный экземпляру 0x890ae90 Программа получила сигнал "SIGABRT".

Если я могу полностью идентифицировать уведомление, подлежащее отмене, почему оно мне это дает?

Ответы [ 2 ]

12 голосов
/ 04 февраля 2012

В моем приложении я сделал это так:

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

И когда я запланировал локальное уведомление, я добавил ключ.FlightNo - это уникальный идентификатор для уведомления.

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

localNotif.userInfo = infoDict;

Примечание от Ника Фарина : работает только для запланированных уведомлений;Вы не можете отменить уведомление, представленное через presentLocalNotificationNow:

3 голосов
/ 05 февраля 2012

Я нашел способ сделать его немного лучше.Если вы хотите удалить localNotification прямо из таблицы, вы можете добавить кнопку «отмена» или «удалить» в каждую ячейку.вот так:

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

И затем вы кодируете свою кнопку:

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

Это просто еще один способ сделать это.Мне кажется, немного лучше визуализировать.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...