从目标日期开始的2天之前的NSNotification

时间:2012-08-31 03:40:47

标签: iphone objective-c ios xcode

我想在目标日期的2天之前发出通知。目前我使用下面的代码来发送通知,但是如何在目标日期的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.

2 个答案:

答案 0 :(得分:1)

您应该使用NSCalendar和NSDateComponents来进行数学运算 - 例如:

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

答案 1 :(得分:0)

您可以通过NSCalendar类对日历日期(年/月/日/小时......在给定时区中的表示)进行算术运算。虽然在大多数情况下,“24 * 60 * 60”秒将是一天 - 用户可能不会注意到差异。