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

8

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

我已经尝试过这个方法。使用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];

}

我在这里将模拟器位置设置为8.0版本的iPhone 4s模拟器,但即使在实际设备上也无法工作。

@所有人 请告诉我,在这里我做错了什么。

4个回答

5

我解决了IOS 8.0的问题。

手动将NSLocationAlwaysUsageDescription添加到应用程序的plist文件中,将字符串值留空。这将调用委托方法。不能忘记添加NSLocationAlwaysUsageDescription,否则该委托方法将无法正常工作。其余代码相同,添加委托方法到控制器类中。

在locationManager声明代码中添加以下代码行,适用于 IOS 8.0:      [locationManager requestAlwaysAuthorization];


3
在iOS 8中,这段代码会静默失败,即您不会收到任何错误或警告信息。
如果要使位置服务正常工作,需要执行两个额外的步骤:
1. 在Info.plist中添加一个密钥。 2. 请求授权让位置管理器开始运行。
在Info.plist文件中必须添加以下任意一个或两个密钥:
1. NSLocationWhenInUseUsageDescription 2. NSLocationAlwaysUsageDescription
这些密钥的类型是字符串,其值可以是任何消息描述或为空。
现在您需要请求相应位置方法的授权。使用以下任意一个方法之一:
1. [self.locationManager requestWhenInUseAuthorization] 2. [self.locationManager requestAlwaysAuthorization]

0

是的,模拟器提供了一个过于简化的位置服务版本。真正测试CLLocationManager行为的唯一方法是使用物理设备。

问题在于,当您调用startUpdatingLocation时,并不意味着您可以立即检索到location。(我认为您会发现它要么是nil,要么具有负horizontalAccuracy,这意味着尚未确定位置。)

您必须遵循CLLocationManagerDelegate,并实现locationManager:didUpdateLocations:,该方法是异步调用的。因此,在尝试使用位置信息之前,您必须等待调用此方法。请注意,在真实设备上,随着设备精度的提高(例如,您可能会看到horizontalAccuracy数字从一个位置更新到另一个位置),您可能会看到此方法被多次调用。


显然,您可能还希望实现locationManager:didFailWithError:以便检测问题。在调用startUpdatingLocation之前,您可能还应该检查authorizationStatuslocationServicesEnabled并调用requestWhenInUseAuthorization

0

看起来我们需要完成一些任务才能在ios8中实现位置服务。 跟随这个讨论


添加了委托方法didFailWithError和didUpdateToLocation,但是这些方法根本没有触发。 - KkMIW
请在您的.h文件中添加CLLocationManagerDelegate,像这样:@interface DemoViewController : UIViewController<CLLocationManagerDelegate> - Samin
我添加了CLLocationManagerDelegate,但仍然存在问题。在将SDK从IOS 7升级到IOS 8后出现了一些问题。 - KkMIW

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接