如何在IOS SDK 8.0中获取当前位置的经度和纬度

时间:2014-10-01 18:22:14

标签: ios8 core-location cllocationmanager cllocation currentlocation

如何获取当前位置的纬度和经度。

我试过这个。使用Xcode 6.01和IOS SDK 8.0

-(CLLocationCoordinate2D) getLocation{
    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    locationManager.distanceFilter = kCLDistanceFilterNone;
    [locationManager startUpdatingLocation];
    CLLocation *location = [locationManager location];
    CLLocationCoordinate2D coordinate = [location coordinate];
    return coordinate;
}

- (void)getCurrentLocation{    
    CLLocationCoordinate2D coordinate = [self getLocation];
    NSString *latitude = [NSString stringWithFormat:@"%f", coordinate.latitude];
    NSString *longitude = [NSString stringWithFormat:@"%f", coordinate.longitude];
    NSLog(@"Latitude  = %@", latitude);
    NSLog(@"Longitude = %@", longitude);
}


- (void)viewDidLoad{
    [super viewDidLoad];
    [self getCurrentLocation];

}

这里我将模拟器位置启用到Deployment 8.0 iPhone模拟器4s。 即使在设备上也无法正常工作。

@ALL 请让我知道,我在这里做错了什么。

4 个答案:

答案 0 :(得分:5)

我在IOS 8.0中找出了问题

NSLocationAlwaysUsageDescription 将此手动添加到应用程序plist文件中,将字符串值保留为空。 这将调用委托方法。永远不要忘记添加 NSLocationAlwaysUsageDescription ,除非您没有添加此委托方法将无法正常工作。剩下的代码是一样的。将委托方法添加到控制器类。

在locationManager声明代码中添加此行代码。对于IOS 8.0      [locationManager requestAlwaysAuthorization];

答案 1 :(得分:3)

在iOS 8中,此代码无声地失败,即您不会收到任何错误或警告。

您需要做两件额外的事情才能让位置正常工作:

  1. 在Info.plist中添加密钥
  2. 来自位置经理的
  3. 请求授权,要求启动。
  4. 需要在Info.plist文件中添加以下任何一个或两个键。

    1. NSLocationWhenInUseUsageDescription
    2. NSLocationAlwaysUsageDescription
    3. 这些是String类型,值可以是任何消息描述或为空。

      现在您需要请求相应位置方法的授权。使用以下任何一种电话:

      1. [self.locationManager requestWhenInUseAuthorization]
      2. [self.locationManager requestAlwaysAuthorization]

答案 2 :(得分:0)

是的,模拟器提供了过度简化的位置服务再现。物理设备是真正测试CLLocationManager行为的唯一方法。

问题在于,当您致电startUpdatingLocation时,并不意味着您可以立即检索location。 (我认为您会发现nil或者horizontalAccuracy为负,这意味着该位置尚未确定。)

您必须符合CLLocationManagerDelegate,并实施locationManager:didUpdateLocations:,这是异步调用的。因此,在尝试使用位置信息之前,必须等待调用此方法。并且,请注意,在真实设备上,您可能会看到此方法被调用多次,因为设备会提高设备位置信息,并且准确性会提高(例如,您可能会看到horizontalAccuracy号从一个位置更新到另一个位置更新)。


显然,您可能也希望实现locationManager:didFailWithError:,因此可以检测到问题。在致电authorizationStatus之前,您可能还应该检查locationServicesEnabledrequestWhenInUseAuthorization并致电startUpdatingLocation

答案 3 :(得分:0)

看来我们需要做更多的任务来在ios8中实现位置服务。 follow this discussion