苹果文档中的旧方法似乎仍然适用于 iOS6(在我的活动应用程序中没有注意到这一点(它通过 gps 跟踪用户的路线))
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];
if (locationAge > 5.0) return;
if (newLocation.horizontalAccuracy < 0) return;
// proceed with coords here
}
讨论中的更新:计算总距离和当前距离可以这样完成(不包括一些小东西):
// somewhere at the top
CLLocation* lastUsedLocation = nil; // last location used in calculation
CLLocation* pointA = nil; // start of the track
double totalDistance = 0; // total distance of track
double currentDistance = 0; // distance between startTrack point and current location
...
// when you start updating location:
- (void) startTracking {
lastUsedLocation = nil;
pointA = nil;
totalDistance = 0;
currentDistance = 0;
[locationManager startUpdatingLocation];
}
...
// location update callback
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];
if (locationAge > 5.0) return; // filter cached
if (newLocation.horizontalAccuracy < 0) return; // filter invalid
if(!pointA) pointA = [newLocation retain];
if(lastUsedLocation)
{
totalDistance += [newLocation distanceFromLocation:lastUsedLocation];
}
currentDistance = [pointA distanceFromLocation:newLocation];
[lastUsedLocation release];
lastUsedLocation = [newLocation retain];
}
如果您需要故意关闭后台位置的选项,您可以手动禁用它,例如:
- (void)applicationDidEnterBackground:(UIApplication *)application {
if(backgroundLocationDisabled)
{
[locationManager stopUpdatingLocation];
// additional stuff
}
}