Search code examples
iphonetimestampcllocation

Force location update


I'm attempting to overcome a sometimes-failure of didUpdateToLocation when checking local data based on current position, closing the app, traveling a bit, and opening the app again. What happens is that the user visits one place, checks the list, goes to another place, and the list is updated but using the old location data.

I would like to make sure I have a fresh newLocation.

What's wrong with this code?

double aa,bb,cc;

-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    [manager stopUpdatingLocation]; //only stop if new reliable pos fetched.
        //old data? retry.
    aa=[newLocation.timestamp timeIntervalSinceReferenceDate];
    bb=[NSDate timeIntervalSinceReferenceDate];
    cc=bb-aa;   //must be <60 - minute-fresh
    if (cc>60) {
        [manager stopUpdatingLocation]; //only stop if new reliable pos fetched.
        [manager startUpdatingLocation];    //only stop if new reliable pos fetched.
        return;
    }
...handle position
}

The symptoms are that cc is about 1200 seconds on app start, then on each retry it increases a few seconds.

I've tried -[newLocation.timestamp timeIntervalSinceNow], and similarly it increases a few seconds at each retry. At one point the interval was ~2400.

I'm using FilterNone and AccuracyBest, if that could influence it.

I'm open to alternative code solutions to make sure you have a fresh position.


Solution

  • The answer was that you need to write the handling the way you want it to behave.

    I've read up on this common problem. I should have clarified that "force" means to start unambiguous behavior that gives a reliable position under optimal conditions for the phone. Not to busy-wait until satisfied or to expect an immediate result/error code.

    From a common sense viewpoint, what would be desirable by all developers would be at least an extra method to simply ask for a position within parameters, and callback only when it's valid and within accuracy, or canceled, or timed out. If the conditions prevent it you then don't need to test out esoteric behavior to be able to handle it with custom code.

    Why I needed to ask about this at all was:

    1. no existence of a method functioning as described above

    2. using code from a book (More Iphone 3 Development)

    3. when writing it from scratch (looking at LocateMe.xproj), discovering that:

    4. simulator behavior differs from phone behavior (not talking about the position itself, which is obviously as good as ip lookup can make it, but the behavior of didUpdateToLocation). Recognizing the limitations of a simulator, the method should at least behave like they do on a device. But currently, correctly written location handling/checking code just times out in the simulator (as in the LocateMe example), while incorrect code (asking once and using newLocation on callback) works.

    5. and a bug causing didUpdateToLocation being called twice after [locationManager stopUpdatingLocation];

    If on top of this you (like I) load data based on your position, and the data is required by multiple views in your application, the behavior of Apple's location-fetching methods doesn't make it easy to handle the chain of update-load-calculate-present consistently and problem-free throughout the app. Especially if your stuck between user/boss perception or decision of how it should work (a rock) and how the system works (a hard place).

    Here's my current code which works on a device and in a simulator:

    //ask for a position, as fresh as possible.
    -(void)updateMeMap {
        lastloc.coordinate=homeloc.coordinate;
        lm.delegate=self;
        ctr=0;
        [self performSelector:@selector(stopUpd) withObject:nil afterDelay:gpstimeout];
        [lm startUpdatingLocation];
    }
    
    //called on each position update.
    -(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
        ctr++;
        if (ctr<15) {
            NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];
            NSLog(@"%d",ctr);
            if (locationAge<60) {
                NSLog(@"Found");
                ctr=40;
                homeloc.coordinate=newLocation.coordinate;
                [self stopUpd];
                [self reload];
            } else {
                NSLog(@"Lastupd");
                lastloc.coordinate=newLocation.coordinate;
            }
        } else {
                //enough tries, if not canceled choose lastloc.
            if (ctr<40) {
                NSLog(@"Last");
                ctr=40;
                homeloc.coordinate=lastloc.coordinate;  
                [self stopUpd];
                [self reload];
            }
        }
    }
    
    //force stop updates. ctr prevents extra calls after stopUpdatingLocation.
    //called after the timeout delay, if position found, cancel the timeout.
    -(void)stopUpd {
        [lm stopUpdatingLocation];
        lm.delegate=nil;
        if (ctr<15) {
            ctr=40; //2 extra calls after stopupda... otherwise, now do nothing.
            NSLog(@"Timeout");
            homeloc.coordinate=lastloc.coordinate;  //@need "copy"?
            [self reload];
        } else {
            ctr=40; //2 extra calls after stopupda... otherwise, now do nothing.
            [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(stopUpd) object:nil];
        }
    }
    
        // "couldn't get userlocation" handler. I also cancel like this on connectionDidFailWithError.
    -(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
        NSLog(@"Location failed: %@",[error localizedDescription]);
        ctr=0;
        [self stopUpd];
    }
    

    Where ctr is there to prevent the 2 extra calls, lastloc is last known reliable position, homeloc is the phone position used for (threaded) loading of location-specific data with [self reload].

    The constants 15 and 60 are safe values from real-world testing; gpstimeout is set to 30. If you work a lot in a simulator you may want to set it to something short like 3 seconds, as all you will get is a stale but relatively usable position and no more until the timeout.

    Edit: If you can best my code or point out an omission, I'll mark that as answer, I hate marking my own as answer.