【问题标题】:CLLocationManager always returns the exact same locationCLLocationManager 总是返回完全相同的位置
【发布时间】:2014-07-18 20:05:31
【问题描述】:

我正在尝试设置新的 CLLocation 和 CLRegion,但无论我实际在哪里,该位置总是以相同的坐标返回。我的主 UIViewController 符合 CLLocationManagerDelegate 协议,自定义类也是如此。当自定义类初始化时,我将计时器设置为在 0.25 秒后触发,代码如下:

mainLocationManager = [[CLLocationManager alloc] init];
[mainLocationManager startUpdatingLocation];
location = [mainLocationManager location];
if (![location.timestamp isEqualToDate:[NSDate dateWithTimeIntervalSinceNow:0]]) { //filters cached data by updating location if cached data not recent enough
    location = [mainLocationManager location];
}

//Set up region
region = [[CLRegion alloc] initCircularRegionWithCenter:location.coordinate
                                                     radius:500
                                                 identifier:[NSString stringWithFormat:@"region:%@", locationName]];
NSLog(@"%@       %@", location, region);

代码似乎可以工作,只是坐标始终是相同的值。我不知道如何改变这一点。任何帮助表示赞赏,谢谢!

【问题讨论】:

  • 坐标是多少?他们是你的实际位置吗?你是在设备还是模拟器上运行它?
  • 您尝试同步获取它 - 错误。 API 是异步的。照多米尼克或邓肯说的做

标签: ios objective-c cllocationmanager cllocation clregion


【解决方案1】:

位置管理器是一个异步框架。您不能调用 startUpdatingLocation 然后立即期望位置管理器拥有用户的正确位置。

您必须将自己设置为位置管理员的委托,调用 startUpdatingLocation,然后等待它调用您的locationManager:didUpdateToLocation:fromLocation: 方法。事实上,您需要检查您获得的位置更新并拒绝旧的、陈旧的位置信息或过于不准确的位置更新(当您第一次打开位置更新时,您获得的第一个更新是从上次 GPS 处于活动状态时开始的,有时会过时数小时或数天。然后,在 GPS 稳定下来并开始提供良好读数之前,下一次更新非常不准确。)

【讨论】:

    【解决方案2】:

    为了让它工作,你需要实现委托:

    locationManager:didUpdateLocations:
    

    另见here

    为了正确使用:

    How to get current location using CLLocationManager in iOS

    【讨论】:

      【解决方案3】:

      我认为是因为您没有通过位置管理器委托方法更新位置。

      通过此方法获取更新位置

      -(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
      
      {
      location_updated = [locations lastObject];    
      NSLog(@"updated coordinate are %@",location_updated);
      
      }
      

      也在设备中测试它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多