Darren Darren - 1 year ago 151
iOS Question

UILocalNotification is supposed to repeat every weekday, but fires on weekends as well

I have a UILocalNotification that is supposed to fire once a day, Monday through Friday, but not on the weekend. I thought that setting the repeatInterval property of the notification to NSWeekdayCalendarUnit would accomplish this. Sadly for me, my notifications are still firing on the weekend. Can anyone suggest why? Here is my code:

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

localNotification.alertAction = @"View";
localNotification.alertBody = NSLocalizedString(@"ALERT_MESSAGE", nil);
localNotification.soundName = UILocalNotificationDefaultSoundName;

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM-dd-yyyy HH:mm"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"America/Toronto"]];

// Notification fire times are set by creating a notification whose fire date
// is an arbitrary weekday at the correct time, and having it repeat every weekday
NSDate *fireDate = [dateFormatter dateFromString:@"01-04-2012 11:00"];

localNotification.fireDate = fireDate;
localNotification.repeatInterval = NSWeekdayCalendarUnit;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

[localNotification release];

Answer Source

Weekday in iOS just means a day inside of a week. It doesn't have the "work week" connotation as opposed to a weekend.

The documentation says it a little clearer, by suggesting that you use 1-7 as the units:


Specifies the weekday unit.

The corresponding value is an kCFCalendarUnitSecond. Equal to kCFCalendarUnitWeekday. The weekday units are the numbers 1 through N (where for the Gregorian calendar N=7 and 1 is Sunday).

Source: http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSCalendar_Class/Reference/NSCalendar.html

To properly set your notifications from Monday through Friday, here's some skeleton code. Yo'll have to execute it 5 times, so it'd be good to encapsulate it inside of a method that parameters for the fireDate. I've shown how you could do it for Monday.

UILocalNotification *notification = [[[UILocalNotification alloc] init] autorelease];

// Set this to an NSDate that is for the time you want, on Monday
notification.fireDate = fireDate;            

// Repeat every week
notification.repeatInterval = NSWeekCalendarUnit;