How do I create and cancel unique UILocalNotification from a custom class?

China☆狼群 提交于 2019-11-28 18:27:25

The answer to your problem lies in the userInfo dictionary parameter that every UILocalNotification has. You can set values for keys in this dictionary to identify the notification.

To implement this easily all you have to do is have your timer class have an NSString "name" property. And use some class wide string for the key for that value. Here is a basic example based on your code:

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

This implementation should be relatively self explanatory. Basically when an instance of the timer class has -scheduleAlarm called and it is creating a new notification it sets it's string property "name" as the value for the kTimerNameKey. So when this instance calls -cancelAlarm it enumerates the array of notifications looking for a notification with it's name for that key. And if it finds one it removes it.

I imagine your next question will be how to give each of your timers name property a unique string. Since I happen to know you are using IB to instantiate them (from your other question on the matter) you would likely do this in viewDidLoad something like:

self.timerA.name = @"timerA";
self.timerB.name = @"timerB";

You could also tie the name property in with a title label you may have.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!