【发布时间】:2014-03-09 11:51:20
【问题描述】:
我正在使用 CLLocationManager 获取设备的当前位置,并尝试获取 location 属性以获取经度和纬度,如下所示:
-(void)getCurrentLocation{
CLLocationManager *manager=[[CLLocationManager alloc]init];;
manager.delegate=self;
manager.desiredAccuracy=kCLLocationAccuracyBest;
self.currentLocation=manager.location;
NSLog(@"Current Lat :%f",self.currentLocation.coordinate.latitude);
NSLog(@"Current Long :%f",self.currentLocation.coordinate.longitude);
[manager startUpdatingLocation];
}
鉴于:
self.currentLocation is a property inside my class (Which is the CLLocationManagerDelegate) as follows:
.h
@property(nonatomic,strong) CLLocation *currentLocation;
.m中的getter如下:
-(CLLocation *)currentLocation{
if (!_currentLocation) {
_currentLocation=[[CLLocation alloc]init ];
}
return _currentLocation;
}
忘了说我实现了didUpdateToLocation方法如下:
-(void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
NSLog(@"didUpdateToLocation");
CLLocation *loc=newLocation;
if (loc!=nil) {
self.currentLocation=loc;
}
}
我也尝试在startUpdateLocation 调用之后将此声明:
self.currentLocation=manager.location;
问题是,当我调用前面的函数 getCurrentLocation 时,它里面的两个 NSLog 会打印 0.000000,这意味着 manager.location 不起作用,奇怪的是 didUpdateToLocation 里面的第一个 NSLog 没有t打印,提前谢谢
【问题讨论】:
-
您应该实现
CLLocationManagerDelegate方法(特别是locationManager:didUpdateLocations:),然后等到您被调用。您应该将启动位置管理器并等待响应的过程视为异步过程。 -
请注意,从 iOS 6.0 开始,didUpdateToLocation 已被弃用!改用我的示例中的 didUpdateLocations 。您的问题是直到稍后的时间点才会调用您的委托方法。可能是 10 毫秒或几秒钟。取决于 GPS 信号等。尝试将您的 NSLog 调用移动到委托方法,如下面的示例中实现的那样。
标签: objective-c ios7 core-location