Reputation: 4980
I wrote an app lets the user enter in a date on a date picker, and they will press a button to schedule a local notification 3 days before the date is approaching. The only issue is, how would I edit this code to not factor in the year that the user types in? Because they may type in something like 1980 for the year, which obviously has already passed.
I tried deleting [dateComps setYear:[dateComponents year]];
, but that causes the notification to fire immediately. I also tried deleting both that and NSYearCalendarUnit from the date components, but the same thing happens. Any help is much appreciated! Here is my code:
- (IBAction)scheduleNotifButton:(id)sender {
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDate *pickerDate = [self.datePicker date];
NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit )
fromDate:pickerDate];
NSDateComponents *timeComponents = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit )
fromDate:pickerDate];
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setDay:[dateComponents day]];
[dateComps setMonth:[dateComponents month]];
[dateComps setYear:[dateComponents year]];
[dateComps setHour:13];
[dateComps setMinute:30];
[dateComps setSecond:[timeComponents second]];
NSDate *itemDate = [calendar dateFromComponents:dateComps];
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
localNotif.fireDate = itemDate;
localNotif.timeZone = [NSTimeZone defaultTimeZone];
localNotif.alertBody = @"Event is in 3 days!";
localNotif.alertAction = nil;
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 0;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
}
Upvotes: 1
Views: 913
Reputation: 3038
As requested:
What if you just ignore the year entered and substitute it with the current year?
Upvotes: 1
Reputation: 4131
you can just get the current year, and set it to your dateComps
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit fromDate:[NSDate date]];
[dateComps setYear:[components year]];
EDIT:
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setDay:[dateComponents day]];
[dateComps setMonth:[dateComponents month]];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit fromDate:[NSDate date]];
[dateComps setYear:[components year]];
[dateComps setHour:13];
[dateComps setMinute:30];
[dateComps setSecond:[timeComponents second]];
NSDate *itemDate = [calendar dateFromComponents:dateComps];
Upvotes: 0