2012-01-03 60 views
2

我想每週晚上10點(不分國家)發出通知。我需要使用時區嗎?目前我正在使用下面的代碼來每週都會觸發通知,但是如何在晚上10點完全觸發通知。特定時間的iPhone本地通知

NSDate *date = [NSDate date]; 
NSDate* myNewDate = [date dateByAddingTimeInterval:7*24*60*60];  
UILocalNotification *localNotification = [[UILocalNotification alloc] init]; 
localNotification.fireDate = myNewDate; 
localNotification.timeZone = [NSTimeZone defaultTimeZone]; 
localNotification.repeatInterval = NSWeekCalendarUnit; 
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification]; 
[localNotification release]; 

回答

4

我認爲,你想要得到的通知(而不是「從現在開始一週」),會做你想要的一天,你fireDate設置爲22:00。你可能會想用NSCalendar來做到這一點。

NSDateComponents *dateComponents = [[NSDateComponents alloc] init]; 
NSDate *currentDate = [NSDate date]; 
NSDate *fireDate = nil; 

[dateComponents setDay:3]; // ...or whatever day. 
[dateComponents setHour:22]; 
[dateComponents setMinute:0]; 

fireDate = [gregorian dateByAddingComponents:dateComponents 
             toDate:currentDate 
            options:0]; 

[localNotification setFireDate:fireDate]; 
[dateComponents release]; 
+0

謝謝你的邏輯? – 2012-01-04 11:18:27

0

我做了這些改變和它的工作...

NSDateComponents *dateComponents = [[NSDateComponents alloc] init]; 
NSDate *currentDate = [NSDate date]; 
NSDate *fireDate = nil; 

//Getting current Hour 
NSDateComponents *components = [[NSCalendar currentCalendar] components:(kCFCalendarUnitHour | kCFCalendarUnitMinute) fromDate:currentDate]; 
NSInteger hour = [components hour]; 
NSInteger minute = [components minute]; 

[dateComponents setDay:7];//After 1 week 
[dateComponents setHour:22-hour-1]; //Calculating Remaining time for 10PM && "-1" because i am adding 60 min 
[dateComponents setMinute:60-minute]; 

//Adding remaining time to current Time 
fireDate = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents 
               toDate:currentDate 
              options:0]; 
[localNotification setFireDate:fireDate];