如何从UILocalNotification对象中获取NEXT开火日期

Jef*_* H. 4 iphone date setinterval uilocalnotification

我有一个UILocalNotification对象,我设置了重复间隔日,周和月.我在访问对象的开火日期时没有任何麻烦:

[cell.detailTextLabel setText:[notification1.fireDate description]];
Run Code Online (Sandbox Code Playgroud)

但是我遇到了下一次火灾日期的麻烦.如果我将上面的notification1对象打印到控制台,我得到这个:

<UIConcreteLocalNotification: 0x613e060>{fire date = 2010-11-29 03:53:52 GMT, time zone = America/Denver (MST) offset -25200, repeat interval = 16, next fire date = 2010-11-30 03:53:52 GMT}
Run Code Online (Sandbox Code Playgroud)

这个对象包含显示下一个开火日期所需的值或数据...但我找不到它!有谁知道我可以通过编程方式获得它?

谢谢

Eri*_*ric 9

要计算重复的下一个开火日期UILocalNotification,您必须:

  1. 弄清楚量repeatInterval有过通知的原始火日期之间的内容(即其fireDate属性)和现在.
  2. 将它们添加到通知中fireDate.

这是一种方法:

NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];

NSDateComponents *difference = [calendar components:notif.repeatInterval
                                           fromDate:notif.fireDate
                                             toDate:[NSDate date]
                                            options:0];

NSDate *nextFireDate = [calendar dateByAddingComponents:difference
                                                 toDate:notif.fireDate
                                                options:0];
Run Code Online (Sandbox Code Playgroud)

这适用于许多场景,但这是一个不起作用的场景:

假设:

  • 通知的`fireDate是01/01在下午2:00
  • 通知repeatIntervalNSDayCalendaryUnit(即每天重复)
  • 现在的日期是08/01下午3:00

上面的代码将计算差异为7天(01/01 + 7天= 08/01),将它们添加到fireDate,并因此设置nextFireDate08/01在下午2点.但那是在过去,我们希望nextFireDate09/01下午2点!

因此,如果使用上面的代码而你的repeatIntervalNSDayCalendaryUnit,那么添加以下行:

if ([nextFireDate timeIntervalSinceDate:[NSDate date]] < 0) {
    //next fire date should be tomorrow!
    NSDateComponents *extraDay = [[NSDateComponents alloc] init];
    extraDay.day = 1;
    nextFireDate = [calendar dateByAddingComponents:extraDay toDate:nextFireDate options:0];
}
Run Code Online (Sandbox Code Playgroud)

我将此答案标记为社区维基,如果您找到了更好的计算方法,请随时编辑它!


Rob*_*und 7

我认为下一个火灾日期不是作为财产提供,而是根据fireDate和计算repeatInterval.对于不同的时区和其他讨厌的事情,日期计算可能会很棘手.在您的示例中,您选择了每日重复并计算下一个开火日期,您可以执行以下操作:

NSCalendar *calendar = localNotif.repeatCalendar;
if (!calendar) {
  calendar = [NSCalendar currentCalendar];
}

NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
components.day = 1;
NSDate *nextFireDate = [calendar dateByAddingComponents:components toDate:localnotif.fireDate options:0];
Run Code Online (Sandbox Code Playgroud)

如果您使用其他重复间隔,则必须相应地更改代码.如果您要使用NSMonthCalendarUnit,则必须使用components.month = 1.

  • 这不是一个正确的答案.这只是向通知初始触发日期添加一个组件元素,它不计算发生重复通知的次数. (7认同)