iphone - 目标日期 2 天前的 NSNotification

标签 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.

最佳答案

您应该使用 NSCalendar 和 NSDateComponents 来进行数学计算 - 类似于:

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

关于iphone - 目标日期 2 天前的 NSNotification,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12208595/

相关文章:

iphone - Cocos2d-iphone 对 iPhone 4 高分辨率的支持

ios - 如何重新加载整个 UIViewController 页面

ios - 在容器 View 中嵌入多个 View Controller

ios - UISegmentedControl上的图像无法正确显示

iphone - 升级时需要卸载Xcode吗?

iphone - 核心数据迁移 - 找不到迁移的映射模型

iphone - 为什么自动生成的 IBOutlet @properties 不使用 @synthesize button = _button 约定?

objective-c - 如何在代码块中编译 Objective-C?

ios - 如何在 IOS 的 Objective-C 中使用对齐区域编程拖放

ios - 如何更改导航栏高度