user1839995
user1839995

Reputation: 113

Cancel all notifications at specific time

For my App I don't want notifications to go off in the weekends. So my idea was to cancel all the notifications at a specific time on Fridays, I would like to do this by scheduling the task, just like I schedule notifications (UILocalNotifications)

So for example I have this code for my alarms:

NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setHour:8];
    [comps setMinute:25];
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *fireDate = [gregorian dateFromComponents:comps];

    UILocalNotification *alarm = [[UILocalNotification alloc] init];

    alarm.fireDate = fireDate;
    alarm.repeatInterval = NSDayCalendarUnit;
    alarm.soundName = @"sound.aiff";
    alarm.alertBody = @"Message..";
    alarm.timeZone = [NSTimeZone defaultTimeZone];
    [[UIApplication sharedApplication] scheduleLocalNotification:alarm];

Is there a way to cancel all the notifications with the same method, or does Apple not allow this?

Upvotes: 1

Views: 243

Answers (2)

mattjgalloway
mattjgalloway

Reputation: 34902

You can cancel a local notification with:

[[UIApplication sharedApplication] cancelLocalNotification:notification];

You would need to loop through all the local notifications and cancel them if they are on the weekend. Loop through them with:

NSArray *notifications = [[UIApplication sharedApplication] scheduledLocalNotifications];
[notifications enumerateObjectsUsingBlock:^(UILocalNotification *notification, NSUInteger idx, BOOL *stop){
    if (/* notification.fireDate is on weekend */) {
        [[UIApplication sharedApplication] cancelLocalNotification:notification];
    }
}];

However you will have to ensure the app runs on a Friday to perform the code to remove the weekend notifications.

But, why not just not schedule ones that are on the weekend in the first place?

Upvotes: 1

Martol1ni
Martol1ni

Reputation: 4702

You can cancel all the local notifications with the method

[[UIApplication sharedApplication] cancelAllLocalNotifications];

If you want to go through them, and maybe post the most important notifications, you could use scheduledLocalNotifications.

Upvotes: 0

Related Questions