2012-01-23 62 views
1

我編寫了一個應用程序,讓用戶在日期選擇器中輸入日期,他們將按下按鈕在日期到來前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]; 

} 
+1

如果您忽略輸入年份並將其替換爲當前年份,該怎麼辦? – onnoweb

+0

謝謝!你能否在答案中寫下這個問題,以便我能夠正確地標記它並按照自己的方式提出一些觀點?感謝你的幫助! – John

回答

1

按照要求:

什麼如果你忽略輸入的年份並用當前年份替代它?

0

你可以得到當年,並將其設置爲你的dateComps

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
NSDateComponents *components = [calendar components:NSYearCalendarUnit fromDate:[NSDate date]]; 
[dateComps setYear:[components year]]; 

編輯:

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]; 
+0

真棒謝謝,所以我應該只是將當前代碼中的nscalendar替換爲上述代碼中的nscalendar,然後在上面的代碼中添加nsdatecomponent?對不起,在這個還是很新的。 – John

+0

看到我的編輯,它應該是類似的東西,但你可以進一步優化它 –