简体   繁体   English

iOS:警报通知的公式

[英]iOS: Formula for alert notifications

I'm trying to write an application that will send the user an alert in the Notification Center 60 hours before the date arrives. 我正在尝试编写一个应用程序,它将在日期到达前60小时在通知中心向用户发送警报。 Here is the code: localNotif.fireDate = [eventDate dateByAddingTimeInterval:-60*60*60]; 这是代码: localNotif.fireDate = [eventDate dateByAddingTimeInterval:-60*60*60];

I was wondering if the -60*60*60 formula will work to alert them 60 hours prior to the date? 我想知道-60*60*60公式是否会在日期前60小时提醒他们? I'm not sure at all how the formula works, I would like to set it up to alert 10 minutes before the date for testing purposes, then change it back to 60 hours once I confirm that everything is correct. 我根本不确定配方是如何工作的,我想把它设置为在测试日期前10分钟发出警报,然后在确认一切正确后再将其更改回60小时。 Does any one know the formula to use for both of these? 有没有人知道用于这两者的公式?

Any help is much appreciated, thank you! 非常感谢任何帮助,谢谢!

A crude but easy-to-code way is to add/subtract seconds from an NSDate directly: 原始但易于编码的方法是直接从NSDate添加/减去秒:

NSDate *hourLaterDate = [date dateByAddingTimeInterval: 60*60];
NSDate *hourEarlierDate = [date dateByAddingTimeInterval: -60*60];

You can see how it works by logging the dates: 您可以通过记录日期来了解它的工作原理:

NSDate *now = [NSDate date];
NSDate *hourLaterDate = [now dateByAddingTimeInterval: 60*60];
NSLog(@"%@ => %@", now, hourLaterDate);

In this approach a date is interpreted as a number of seconds since the reference date. 在此方法中,日期被解释为自参考日期以来的秒数。 So, internally it's just a big number of type double . 所以,在内部它只是一个很大的类型double

A tedious-to-code but pedantically correct way to do these calculations is by interpreting dates as dates expressed in a calendar system. 执行这些计算的繁琐代码但非常正确的方法是将日期解释为日历系统中表示的日期。 The same thing achieved as calendrical calculations: 与日历计算相同的事情:

NSDateComponents *hour = [[NSDateComponents alloc] init];
[hour setHour: 1];
NSCalendar *calendar= [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDate *hourLaterDate = [calendar dateByAddingComponents: hour 
                                                  toDate: date 
                                                 options: 0];
[hour release];
[calendar release];

These calculations take into account time zones, daylight saving time, leap years, etc. They can also be more expressive in terms of what you're calculating. 这些计算考虑了时区,夏令时,闰年等。根据您的计算方式,它们也可以更具表现力。

Before using any of these approaches you have to decide what exactly you need: a timestamp or a full-blown calendar date. 在使用任何这些方法之前,您必须确定您需要什么:时间戳或完整的日历日期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM