Registering Notification in iPhone SDK 3.0
Assuming you have NSDate
in a variable date
and want to run the method dateIsHere:
on that date, do this:
NSTimer* timer = [[NSTimer alloc] initWithFireDate:date
interval:0.0f
target:self
selector:@selector(dateIsHere:)
userInfo:nil
repeats:NO];
[[NSRunLoop mainRunLoop] addTimer:timer
forMode:NSDefaultRunLoopMode];
[timer release];
source to share
Configure NSTimer
that runs the selector every 30 seconds (or whatever granularity you need):
[NSTimer scheduledTimerWithTimeInterval:30.0 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];
The selector (method) -timerFired:
will run every thirty seconds and check the hour, minute and second components, triggering a notification if the items match the requested time:
- (void) timerFired:(NSNotification *)notification {
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSCalendarUnit unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDate *date = [NSDate date];
NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:date];
NSInteger hour = [dateComponents hour];
NSInteger min = [dateComponents minute];
NSInteger sec = [dateComponents second];
if ((hour == kDesiredHour) && (min == kDesiredMinute) && (sec == kDesiredSecond)) {
[[NSNotificationCenter defaultCenter] postNotificationName:@"kTimeComponentsWereMatched" object:nil userInfo:nil];
}
}
You register to listen to this notification in some other class:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doSomething:) name:@"kTimeComponentsWereMatched" object:nil];
Accordingly, you have a method in the same class that does something interesting:
- (void) doSomething:(NSNotification *)notification {
// do something interesting here...
}
You can combine this code if it's all in one class. Or specify target
in NSTimer
to indicate the instance of the class you want to run on selector
.
source to share
I am assuming that you want this timer to fire even when the application is closed. You can use a notification to do this, but you must have a server where the notification was sent.
In addition, the iPhone will pull up a warning to tell the user to open the app, but they might not.
source to share