简体   繁体   中英

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. Here is the code: 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? 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. 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 *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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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