2012-04-22 50 views
4

我正在使用Xcode 4.3.2,如何在每天早上6點設置本地通知「dateToFire」?xcode - 按時間安排本地通知(每天早上6點)

-(void)notification 
{ 
    UILocalNotification *localNotification = [[[UILocalNotification alloc] init] autorelease]; 

    if (!localNotification) 
     return; 

    // Current date 
    NSDate *date = [NSDate date]; 
    NSDate *dateToFire = //Everyday: 6AM; 

    // Set the fire date/time 
    [localNotification setFireDate:dateToFire]; 
    [localNotification setTimeZone:[NSTimeZone defaultTimeZone]]; 
    [localNotification setAlertBody:@"Notification" ];  

    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification]; 
} 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    [self notification]; 
} 

回答

6

使用CalendarComponents到小時設置爲6,並設置localNotification.repeatInterval到NSDayCalendarUnit

NSCalendar *calendar = [NSCalendar currentCalendar]; // gets default calendar 
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:[NSDate date]]; // gets the year, month, day,hour and minutesfor today's date 
[components setHour:18]; 
[components setMinute:0]; 

localNotification.fireDate = [calendar dateFromComponents:components]; 
+0

感謝您的快速回復,但它有一些錯誤。 1.未找到class method'+ calendar'(返回類型默認爲'id')2.使用未聲明的標識符'NSMinuteCalendarComponents'。 – shebi 2012-04-22 08:38:47

+0

NSMinuteCalendarComponents是NSMinuteCalendarUnit,對不起) – 2012-04-22 08:41:08

+0

和日曆應該是currentCalendar) – 2012-04-22 08:41:30