如何从自定义类创建和取消唯一的UILocalNotification?

Mic*_*all 11 objective-c ios uilocalnotification

目前我有一个带闹钟的计时器(本地通知).

我想从这段代码创建一个计时器类来创建多个计时器和通知(最多5个),我正在努力学习如何使用类方法创建和取消唯一通知.

- (UILocalNotification *) startAlarm {

    [self cancelAlarm]; //clear any previous alarms

    alarm = [[UILocalNotification alloc] init];
    alarm.alertBody = @"alert msg"
    alarm.fireDate = [NSDate dateWithTimeInterval: alarmDuration sinceDate: startTime]; 
    alarm.soundName = UILocalNotificationDefaultSoundName; 

    [[UIApplication sharedApplication] scheduleLocalNotification:alarm];

}
Run Code Online (Sandbox Code Playgroud)

我的假设是,如果我有一个创建名为"alarm"的UILocalNotification的类方法,iOS会将所有通知视为相同的通知,并且以下方法将无法按照我希望的方式运行:

- (void)cancelAlarm {

    if (alarm) {    
        [[UIApplication sharedApplication] cancelLocalNotification:alarm];
    }

}
Run Code Online (Sandbox Code Playgroud)

所以我需要一种方法来命名这些UILocalNotifications,因为它们被创建,例如alarm1 alarm2 ... alarm5所以我可以取消正确的.

提前致谢.

NJo*_*nes 32

你的问题的答案在于userInfo每个人UILocalNotification都有的字典参数.您可以在此词典中设置键的值以标识通知.

要轻松实现这一点,您所要做的就是让您的计时器类具有NSString"名称"属性.并使用一些类宽字符串作为该值的键.以下是基于您的代码的基本示例:

#define kTimerNameKey @"kTimerNameKey"

-(void)cancelAlarm{
    for (UILocalNotification *notification in [[[UIApplication sharedApplication] scheduledLocalNotifications] copy]){
        NSDictionary *userInfo = notification.userInfo;
        if ([self.name isEqualToString:[userInfo objectForKey:kTimerNameKey]]){
            [[UIApplication sharedApplication] cancelLocalNotification:notification];
        }
    }
}
-(void)scheduleAlarm{
    [self cancelAlarm]; //clear any previous alarms
    UILocalNotification *alarm = [[UILocalNotification alloc] init];
    alarm.alertBody = @"alert msg";
    alarm.fireDate = [NSDate dateWithTimeInterval:alarmDuration sinceDate:startTime]; 
    alarm.soundName = UILocalNotificationDefaultSoundName; 
    NSDictionary *userInfo = [NSDictionary dictionaryWithObject:self.name forKey:kTimerNameKey];
    alarm.userInfo = userInfo;
    [[UIApplication sharedApplication] scheduleLocalNotification:alarm];
}
Run Code Online (Sandbox Code Playgroud)

这种实现应该是相对自我解释的.基本上,当一个timer类的实例已经-scheduleAlarm调用并且它正在创建一个新的通知时,它会将它的字符串属性"name"设置为kTimerNameKey.因此,当此实例调用-cancelAlarm它时,它会枚举通知数组,以查找包含该键名称的通知.如果它找到一个它删除它.

我想你的下一个问题是如何给你的每个计时器name属性一个唯一的字符串.因为我碰巧知道你正在使用IB来实例化它们(从你关于此事的其他问题),你可能会这样做viewDidLoad:

self.timerA.name = @"timerA";
self.timerB.name = @"timerB";
Run Code Online (Sandbox Code Playgroud)

您还可以将name属性与您可能拥有的标题标签绑定在一起.