如何防止取消所有本地通知。取消单一通知也不起作用

时间:2012-05-02 09:39:20

标签: iphone objective-c push-notification uilocalnotification

我有一个表视图,如下所示我使用

上的相应开关为每个单元设置了提醒
-(IBAction)switchingbtn:(id)sender
{
    UISwitch *onoff = (UISwitch *) sender;
    UILocalNotification *localNotif = [[UILocalNotification alloc] init];
    if(onoff.on)
    {
        NSLog(@"Shedule notification");


    int tagValue=[sender tag];

    NSMutableDictionary *dict = (NSMutableDictionary *)[alarmsArray objectAtIndex:tagValue];


    NSDate *firedate = [dict objectForKey:@"date"];
    NSLog(@"fire date is %@", firedate);
    localNotif.fireDate = firedate;

    localNotif.alertBody = @"Start Exercise";
    localNotif.applicationIconBadgeNumber = 0;

    // localNotif.timeZone =[NSTimeZone timeZoneForSecondsFromGMT:0];
    localNotif.timeZone = [NSTimeZone systemTimeZone];
    localNotif.repeatInterval = kCFCalendarUnitDay;


   //  [[UIApplication sharedApplication] scheduleLocalNotification:localNotif]; //**Not working**
    [localNotif release];

}

不,我需要取消前第3次取消第3次通知的预先通知

else
    {
// Cancel a notification not works
      //  [[UIApplication sharedApplication] cancelLocalNotification:localNotif];

        [[UIApplication sharedApplication] cancelAllLocalNotifications];
    NSLog(@"cancel notification");
}

2 个答案:

答案 0 :(得分:1)

到目前为止取消单个通知的最佳方法是创建一个包含userInfo字典的通知,在此字典中,您可以为id键添加通知ID值。您可以跟踪通知ID(存储在plist,sql数据库等中),当您需要删除通知时,您只需要向UIApplication实例询问已安排的通知并按ID过滤,当您找到匹配项时只需要发送该通知的取消方法。

答案 1 :(得分:0)

这是您想要的代码

- (void)CancelExistingNotification {
//cancel alarm
UIApplication *app = [UIApplication sharedApplication];
NSArray *eventArray = [app scheduledLocalNotifications];
for (int i=0; i<[eventArray count]; i++)
{
    UILocalNotification* oneEvent = [eventArray objectAtIndex:i];
    NSDictionary *userInfoCurrent = oneEvent.userInfo;
    NSString *uid=[NSString stringWithFormat:@"%@",[userInfoCurrent valueForKey:@"notificationID"]];
    if ([uid isEqualToString:[NSString stringWithFormat:@"%i",self.notificationID]])
    {
        //Cancelling local notification

        [app cancelLocalNotification:oneEvent];
        break;
    }
}

}

“self.notificationID”来自自定义对象(如alarmObject)上的属性,这些属性在NSUserDefaults应用程序范围内加载。