我編寫了一個應用程序,讓用戶在日期選擇器中輸入日期,他們將按下按鈕在日期到來前3天安排本地通知。唯一的問題是,我如何編輯此代碼,以不考慮用戶輸入的年份?因爲他們可能會輸入類似1980年的東西,這顯然已經過去了。iOS:日期忽略當年的組件
我試過刪除[dateComps setYear:[dateComponents year]];
,但這會導致通知立即觸發。我也嘗試從日期組件中刪除這兩個和NSYearCalendarUnit,但同樣的事情發生。任何幫助深表感謝!這裏是我的代碼:
- (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];
}
如果您忽略輸入年份並將其替換爲當前年份,該怎麼辦? – onnoweb
謝謝!你能否在答案中寫下這個問題,以便我能夠正確地標記它並按照自己的方式提出一些觀點?感謝你的幫助! – John