iPhone - observer / every x seconds
I have an observer like this:
[mapView.userLocation addObserver:self forKeyPath:@"location" options:0 context:NULL];
So a method is called if an user changes his geolocation. But I want that the method should also be called every x seconds, because If the user does not move, the location won't change and so the method won't be called. But I have to do some calculations.
How could开发者_运维技巧 I do that?
Thanks a lot in advance & Best Regards.
Use a timer
NSTimer *timer;
timer = [NSTimer timerWithTimeInterval:30 //seconds
target:self
selector:@selector(myMethodtoRun:)
userInfo:nil // send an object if you want
repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
Later, if you want to cancel the timer, in the method myMethodToRun, you can invalidate
- (void) myMethodToRun:(NSTimer *)timer {
…
if (shouldStopTimer) {
[timer invalidate];
}
}
MKMapView does not give you much control over GPS device. I recommend using CLLocationManager, so you can perform updates whenever you want. Then you could use NSTimer @coneybeare has just suggested.
In CLLocationManager you can set distanceFilter, which, I belive, does the same thing as observer in MKMapView.
精彩评论