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)
这个对象包含显示下一个开火日期所需的值或数据...但我找不到它!有谁知道我可以通过编程方式获得它?
谢谢
要计算重复的下一个开火日期UILocalNotification,您必须:
repeatInterval有过通知的原始火日期之间的内容(即其fireDate属性)和现在.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)
这适用于许多场景,但这是一个不起作用的场景:
假设:
repeatInterval是NSDayCalendaryUnit(即每天重复)上面的代码将计算差异为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];
}
Run Code Online (Sandbox Code Playgroud)
我将此答案标记为社区维基,如果您找到了更好的计算方法,请随时编辑它!
我认为下一个火灾日期不是作为财产提供,而是根据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.
| 归档时间: |
|
| 查看次数: |
4484 次 |
| 最近记录: |