ios - cancelLocalNotification 不起作用

标签 ios objective-c notifications nsuserdefaults localnotification

我的应用程序中有大约 10 个本地通知(不在数组中)及其开关。我用了这段代码

    NSUserDefaults *defaultsB = [NSUserDefaults standardUserDefaults];
    UILocalNotification *notification = [[UILocalNotification alloc]init];

    if (switcher.on == 1) {

        NSCalendar *gregCalendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
        NSDateComponents *dateComponent = [gregCalendar components:NSYearCalendarUnit  | NSWeekCalendarUnit fromDate:[NSDate date]];

        [dateComponent setWeekday:1]; // For sunday
        [dateComponent setHour:[timeHClass.text integerValue]];
        [dateComponent setMinute:[timeMClass.text integerValue]];

        NSDate *fireDate = [gregCalendar dateFromComponents:dateComponent];


        [notification setAlertBody:textClass1.text];
        [notification setFireDate:fireDate];
        notification.soundName = @"bells.mp3";
        notification.repeatInterval = NSWeekCalendarUnit;
        [notification setTimeZone:[NSTimeZone defaultTimeZone]];
        [[UIApplication sharedApplication] scheduleLocalNotification:notification];


        [defaultsB setObject:@"ON" forKey:@"SwitchState"];
    }
    else  {

        UIApplication *app=[UIApplication sharedApplication];
        [app cancelLocalNotification:notification];



        [defaultsB setObject:@"OFF" forKey:@"SwitchState"];

    }

但是当我关闭通知时,通知仍然有效??

我应该将通知保存在 NSUserDefaults 中而不仅仅是开关吗??

如果是,怎么办??

最佳答案

如果您想取消现有通知,您需要通过 [[UIApplication sharedApplication] scheduledLocalNotifications] 获取对它的引用,然后遍历这些通知并找到您想要的通知(可能使用唯一的您在创建期间为其提供的标识符)。

或者,如果您想取消所有通知替换:

[app cancelLocalNotification:notification];

与:

[app cancelAllLocalNotifications];

关于ios - cancelLocalNotification 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31373778/

相关文章:

ios - 更改从场景编辑器添加的 SKLabelNode 的文本

iOS - 如果模型 View 正在呈现,如何不呈现?

ios - 如何在 iOS 中为一组图像制作动画

iphone - COUNT (*) 给出 EXC_BAD_ACCESS

带有大动画 gif 图像的 Android 自定义通知

android - 将 "something"发送到安装了我的应用程序的设备?

ios - 核心数据按年份分组并按日期排序

ios - 除非我禁用自动调整 subview ,否则 UIPickerView 会错误地显示值

ios - NSFetchedResultsController 不会根据请求重新加载数据

android - 如何在Android应用程序中点击后隐藏通知