Question

I can't seem to figure out why this notification is not scheduling on Saturdays... I've tried both NSGregorianCalendar and autoupdatingCurrentCalendar. I'm setting [dateComps setWeekday:7];, but it keeps returning Sundays.

//NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
 NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *timeComponent = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit ) fromDate:reminderTime];
 // Set up the fire time
 NSDateComponents *dateComps = [[NSDateComponents alloc] init];
 [dateComps setYear: 2012];;
 [dateComps setHour: timeComponent.hour];
 [dateComps setMinute: timeComponent.minute];
 [dateComps setSecond:0];
 // Set day of the week
 [dateComps setWeekday:7];
 NSDate *itemDate = [calendar dateFromComponents:dateComps];

 UILocalNotification *notification = [[UILocalNotification alloc] init];
 if (notification == nil)
     return;
 notification.fireDate = itemDate;
 notification.repeatInterval = NSWeekCalendarUnit;
Was it helpful?

Solution

dateComps as you calculate it, does not contain a day or month so that setWeekday is just ignored and itemDate is a date on the first January 2012 (which was a Sunday).

To compute the next Saturday, you can proceed as described in Adding Components to a Date of the "Date and Time Programming Guide":

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

// Weekday of "reminderTime":
NSDateComponents *weekdayComponents = [calendar components:NSWeekdayCalendarUnit fromDate:reminderTime];

// Number of weekdays until next Saturday:
NSDateComponents *componentsToAdd = [[NSDateComponents alloc] init];
[componentsToAdd setDay: 7 - [weekdayComponents weekday]];

NSDate *itemDate = [calendar dateByAddingComponents:componentsToAdd toDate:reminderTime options:0];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top