iphone - 如何从 UILocalNotification 对象获取下一个触发日期

标签 iphone date setinterval uilocalnotification

我有一个 UILocalNotification 对象,我设置了重复间隔天、周和月。我在访问该对象的触发日期时完全没有任何问题:

[cell.detailTextLabel setText:[notification1.fireDate description]];

但我在确定下一次开火日期时遇到了麻烦。如果我将上面的 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}

该对象在某处包含我显示下一个火灾日期所需的值或数据...但我找不到它!有人知道我可以在哪里以编程方式获取它吗?

谢谢

最佳答案

要计算重复 UILocalNotification下一个触发日期,您必须:

  1. 计算出通知的原始触发日期(即其 fireDate 属性)与现在之间的 repeatInterval 时间。
  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];

这在很多情况下都有效,但这里有一个不起作用的情况:

假设:

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

上面的代码将计算差值 7 天 (01/01 + 7 天 = 08/01),将它们添加到 fireDate 中,从而将 nextFireDate 设置为08/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];
}

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

关于iphone - 如何从 UILocalNotification 对象获取下一个触发日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4301184/

相关文章:

iPhone 故障保护多个文件下载

iphone - 如何显示搜索栏的取消按钮?

linux - 如何将此日期格式转换为纪元?

javascript - 每 x 秒多个 XmlHttpRequest

javascript - setInterval 永远不会在函数中触发,并且不知道为什么( Angular )

iphone - 带蓝牙或免提功能的 CTCall

ios - ADInterstitialAd 不适用于 ipad swift

php - 在 PHP 中处理在不同时区存储/显示日期的最佳方法?

javascript - 比较不同格式的日期

javascript - 单击按钮时 ClearInterval 未定义