I would like to ask for advice on stopping a CLLocationManager -startUpdatingLocation. Currently I am considering two methods, but I am unsure which to use and would like to get an idea how other fol开发者_高级运维ks do this:
Method_001:
[locationManager startUpdatingLocation];
[self performSelector:@selector(stopUpdatingLocation:) withObject:@"TimedOut" afterDelay:30];
- Potentially wastes battery life as always runs for 30secs
- If network is slow might not get an accurate location in time
- Feels quite a tidy way to implement the timeout.
Method_002:
[locationManager startUpdatingLocation];
Then inside: -locationManager:didUpdateToLocation:fromLocation:
add:
static int timeOut = 0;
timeOut++;
// Other code that checks for and stops
// when a suitable result, accuracy, age etc is found.
if(timeOut >= 4) {
[[self locationManager] stopUpdatingLocation];
timeOut = 0;
return;
}
- Might not resolve an accurate location in 4 (or less) attempts.
- 4 results might not be returned for CLLocationManager and we never timeout.
- Better on battery life as we stop immediately on a good result.
Just curious?
Not sure exactly what you're trying to do, but I think the CLLocationManager handles these cases internally. Just configure it thus:
locManager.desiredAccuracy = 2000.0f; // 2 kilometers - hope for accuracy within 2 km.
locManager.distanceFilter = 1000.0f; // one kilometer - move this far to get another update
and then in the callback didUpdateToLocation:fromLocation: if you have a positive signbit,
[locManager stopUpdatingLocation]; // stop GPS
EDIT: add signbit
if (signbit(newLocation.horizontalAccuracy)) {
// Negative accuracy means an invalid or unavailable measurement, so punt.
} else {
// this is a usable measurement.
}
Hmm, I think I prefer the first one. I don't know if we can be sure about how often the didUdpateToLocation:
method gets called. I think the time out is more reliable.
Why not to combine both approaches and give a third (i the best result didn't improve in some amount of time)
I wrote a GIT repo on this, which you are free to use https://github.com/xelvenone/M6GPSLocationManager
- If the result accuracy is better than acceptableAccuracy, we are done
- If we get an update on occuracy, we wait maximumWaitTimeForBetterResult to get a better one, - If this doesn't happen, we are done and take the best one
- If we are constantly getting updates, which exceed maximumAttempts, we take th best one (probably we are moving anyway)
- If we don't get any other update in 30 sec, we are done (there won't be probably any other update)
Code
- (void)scopeToCurrentLocationWithAcceptableAccuracy:(CLLocationAccuracy)acceptableAccuracy
maximumWaitTimeForBetterResult:(NSTimeInterval)maximumWaitTimeForBetterResult
maximumAttempts:(NSInteger)maximumAttempts
onCompletion:(M6GPSLocationManagerCompletion)completion;
精彩评论