views:

116

answers:

2

Hello!

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.

+3  A: 

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];
    }
}
coneybeare
Thanks a lot, that works. But I have a little problem. Switching the view in the TabBar or using the back button in the TabBar, the timer runs... How could I stop it in these two cases?
Tim
invalidate the timer on viewDidDisappear and re initiate it on viewDidAppear (coneybeare gets the points; I'm only chiming in because I had a similiar problem)
justin
thanks a lot, that works.
Tim
A: 

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.

Jacek