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

KkM*_*MIW 8 core-location cllocationmanager cllocation currentlocation ios8

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

我试过这个.使用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];

}
Run Code Online (Sandbox Code Playgroud)

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

@ALL请告诉我,我在这里做错了什么.

KkM*_*MIW 5

我在IOS 8.0中找到了问题

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

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


Rob*_*Rob 0

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

问题是,当您调用 时startUpdatingLocation,并不意味着您可以立即检索location. (我想你会发现它要么是nil要么是负数horizontalAccuracy,这意味着位置尚未确定。)

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


显然,您可能也想实现locationManager:didFailWithError:,以便可以检测到问题。您可能还应该在致电之前检查authorizationStatuslocationServicesEnabled并致电。requestWhenInUseAuthorizationstartUpdatingLocation