CLLocationManager didUpdateLocations或didUpdateToLocation

时间:2015-07-27 07:13:13

标签: ios core-location cllocationmanager deployment-target

我的iOS我正在使用CLLocationManager,但我不确定使用哪种委托方法来获取位置更新。有两种方法

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation

- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray *)locations

我知道我应该使用第二个,因为第一个被弃用但我已经将我的应用的部署目标设置为6.0。那么我应该使用哪一个?在附加图片enter image description here中,就在此方法旁边

(void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation

它说6.0。那么它在iOS 6.0中被弃用或者在6.0之前可以使用它意味着什么呢?我的猜测是,我应该使用

- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray *)locations

它应该没问题。有什么建议?

1 个答案:

答案 0 :(得分:0)

我在旧项目中也面临同样的问题,所以我尝试了以下方法,然后为我工作正常

- (void)locationManager:(CLLocationManager *)manager 
    didUpdateToLocation:(CLLocation *)newLocation 
           fromLocation:(CLLocation *)oldLocation

上面的代理在iOS 6中已弃用。现在应使用以下代码:

- (void)locationManager:(CLLocationManager *)manager 
     didUpdateLocations:(NSArray *)locations

为了获得最后一个位置,只需获取数组的最后一个对象:

[locations lastObject]

换句话说,[locations lastObject](新代表)等于newLocation(旧代表)

示例

iOS6及以上

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
CLLocation *newLocation = [locations lastObject];
CLLocation *oldLocation;
if (locations.count >= 2) {
    oldLocation = [locations objectAtIndex:locations.count-1];
} else {
    oldLocation = nil;
}
NSLog(@"didUpdateToLocation %@ from %@", newLocation, oldLocation);

}

如果您在iOS6及以下版本中使用,还可以添加以下方法

 - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
[self locationManager:locationManager didUpdateLocations:[[NSArray alloc] initWithObjects:newLocation, nil]];
}

有关其他参考,请参阅此tutorial