我有一个 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
的下一个触发日期,您必须:
- 计算出通知的原始触发日期(即其
fireDate
属性)与现在之间的repeatInterval
时间。 - 将它们添加到通知的
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”
- 通知的
repeatInterval
为NSDayCalendaryUnit
(即每天重复) - 现在的日期是 08 月 1 日下午 3:00
上面的代码将计算差值 7 天 (01/01 + 7 天 = 08/01),将它们添加到 fireDate
中,从而将 nextFireDate
设置为08/01 下午 2 点。但那已经是过去的事了,我们希望 nextFireDate
为 09/01 下午 2 点!
因此,如果使用上述代码并且您的 repeatInterval
为 NSDayCalendaryUnit
,则添加以下行:
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/