2012-08-31 34 views
0

我想在目標日期前2天之前發出通知。目前我正在使用以下代碼來觸發通知,但是存在如何在定位日期前2天準確觸發通知。NSNotification從目標日期前2天

NSString *frstdate = [[calenderarray objectAtIndex:k] objectForKey:@"date"]; 
    NSLog(@"frstdate..%@",frstdate); 
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
    [dateFormat setDateFormat:@"yyyy-MM-dd"]; 
    NSDate *date = [dateFormat dateFromString:frstdate]; 
    NSLog(@"date..%@",date); 
    NSDate *dateToFire = [[[NSDate alloc] initWithTimeInterval:-24*60*60 sinceDate:date]autorelease]; 
    NSLog(@"dateToFire..%@",dateToFire); 
    UILocalNotification *localNotif = [[UILocalNotification alloc] init]; 
    if (localNotif == nil) 
     return; 
    localNotif.fireDate = itemDate; 
    localNotif.alertAction = @"View"; 
    localNotif.soundName = UILocalNotificationDefaultSoundName; 
    localNotif.applicationIconBadgeNumber = 1; 
    localNotif.userInfo = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Get Food"], @"foodItem", nil] ; 
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotif]; 
    [localNotif release]; 

    Thanks in advance. 
+1

什麼是'itemDate'?你有意在那裏寫'dateToFire'嗎? – user1118321

+0

您是否使用本機日曆應用來添加這些事件 –

+0

是的,我使用本機日曆應用添加事件。 – vishal

回答

0

您可以通過NSCalendar類對日曆日期(年/月/日/小時...表示法)進行算術運算。雖然在大多數情況下,「24 * 60 * 60」秒將是一天 - 用戶可能不會注意到這種差異。

1

您應該使用NSCalendar和NSDateComponents做數學 - 是這樣的:

NSCalendar* calendar = [NSCalendar currentCalendar]; 
NSDateComponents* twoDaysAgo = [[NSDateComponents alloc] init]; 
twoDaysAgo.day = -2; 
NSDate* dateToFire = [calendar dateByAddingComponents:twoDaysAgo toDate:date options:0]; 
+0

感謝它爲我工作.... – vishal

相關問題