首先,请不要叫startUpdatingLocation每一分钟。你会杀死你的用户在他们的设备上的电池寿命。定位服务利用大量的电池电量进行操作。此外,一旦您致电startUpdatingLocation
,它会运行,直到您致电stopUpdatingLocation
。
您可以在CLLocationManager
上设置的属性根据您的需要进行配置。像...
@property(assign, nonatomic) CLLocationDistance distanceFilter
@property(assign, nonatomic) CLLocationAccuracy desiredAccuracy
distanceFilter
描述:产生一个更新事件之前,设备必须水平移动的最小距离(以米为单位测得)。
desiredAccuracy
可以是下列之一:
kCLLocationAccuracyBestForNavigation
kCLLocationAccuracyBest;
kCLLocationAccuracyNearestTenMeters;
kCLLocationAccuracyHundredMeters;
kCLLocationAccuracyKilometer;
kCLLocationAccuracyThreeKilometers;
根据您的CLLocationManager
对象的配置,设备会使用特定的地理位置与硬件等。有时只需使用手机信号塔三角测量就足够了,是获得半精确位置的最快捷方式。其他时候,它可能需要使用GPS,这将很快耗尽电池寿命,并且需要更长的时间才能实现位置,但在大多数情况下更准确。
我会建议启动一个NSTimer,但将它用于您计划的相反。如果CLLocationManager
无法获得足够精确的位置,请在合理的时间后将其用于stopUpdatingLocation
。你不想离开定位服务永远运行。如果将此计时器设置为30秒,将确保它在超时后关闭。
此外,您将需要实现CLLocationManagerDelegate方法:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
在这种方法中,你将需要检查的位置的timestamp
以确保它是最近的事。您还需要检查该位置的horizontalAccuracy
以确保其位于期望的精度范围内。这是一个如何做到这一点的例子...
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
// Ensure we get a recent and accurate location
NSDate * locationTimestamp = [newLocation timestamp];
NSTimeInterval timeDifference = [locationTimestamp timeIntervalSinceNow];
double thirtyMins = (30 * 60 * -1);
BOOL locationTimestampIsCurrent = (timeDifference > thirtyMins);
BOOL isAccurateLocation = (newLocation.horizontalAccuracy <= 3000.00);
if (locationTimestampIsCurrent && isAccurateLocation) {
NSLog(@"Shutting down location services, we have a good locaton.");
[self stopListeningForLocation];
} else {
// Do nothing, let this method be called again with a new "newLocation" to check its validity.
}
}
距离Ios 6的上述方法已被弃用,而不是使用下面的委托方法:
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
为了得到最新的位置简单地获取位置阵列的像这样的最后一个对象:
CLLocation *location = [locations lastObject];
请参阅[在后台获取位置事件](https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/LocationAwarenessPG/CoreLocation/CoreLocation.html#//apple_ref/doc/uid/TP40009 497-CH2-SW10)。你不应该在后台调用'startUpdatingLocation'。但是您必须请求许可才能继续提供位置服务。请参阅[位置讨论](http://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html#//apple_ref/doc/uid/TP40007072-CH4-SW24) – Rob
http://stackoverflow.com/questions/6347503/how-do-i-get-a-background-location-update-every-n-minutes-in-my-ios-application –