【问题标题】:CLLocationManager doesn't get locationCLLocationManager 没有获取位置
【发布时间】: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


【解决方案1】:

您不能只从 CLLocationManager 中读取位置。它需要在分配该属性之前更新其位置:

The value of this property is nil if no location data has ever been retrieved.

CLLocationManager SDK

你必须实现委托方法locationManager:didUpdateLocations:

当它被调用时,您可以读取location 属性,或查看locations 参数:

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    self.currentLocation = [locations firstObject];

    NSLog(@"Current Lat :%f",self.currentLocation.coordinate.latitude);
    NSLog(@"Current Long :%f",self.currentLocation.coordinate.longitude);

    [manager stopUpdatingLocation]
}

您可以在接到第一个电话时拨打[manager stopUpdatingLocation],因此它不会继续运行。

【讨论】:

  • @JavaPlayer 您的问题仍然是您试图在从 GPS 检索到位置之前读取位置。此外,您正在使用已弃用的委托方法,如我上面的评论中所述。尝试实现我上面的委托方法,看看会发生什么。
  • 我试过了,它在模拟器上运行良好,但它在设备上不起作用(没有调用 didUpdateLocations 方法!!)虽然我正在打开设备的定位服务
  • 尝试执行locationManager:didFailWithError: 看看有没有错误。如果它在模拟器中运行,而不是在设备上运行,则一定有问题。
  • locationManager:didFailWithError: 也不能在设备上工作!!
  • 您确定设备上启用了定位服务吗?尝试调用[CLLocationManager authorizationStatus][CLLocationManager locationServicesEnabled] - 看看他们是否分别返回kCLAuthorizationStatusAuthorizedYES
猜你喜欢
  • 1970-01-01
  • 2017-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-18
  • 2016-02-25
相关资源
最近更新 更多