Latidude and Longitude are incorrect first time app is launched ios

时间:2016-04-15 15:19:50

标签: ios cllocationmanager cllocation openweathermap

I am using CLLocationManager to get the user's current location. I need the user's current location because I am using the Open Weather Api to display the weather data wherever the user is. My problem is that the first time I open the app the lat and long value are 0, 0. But then if I run the app again it works fine. So only on the first launch of the app incorrect lat and long values are used. I do all my set up in viewDiDLoad, here is the code...

locationManager = [[CLLocationManager alloc] init];
[locationManager requestAlwaysAuthorization];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
    [self->locationManager requestWhenInUseAuthorization];

[locationManager startUpdatingLocation];

I don't know what I am doing wrong. Is it something to do with getting the lat and long in the view controller instead of App Delegate?

Here is how I am getting the location values:

locationManager.location.coordinate.latitude
locationManager.location.coordinate.longitude

2 个答案:

答案 0 :(得分:1)

您应该检查horizontalAccuracy对象的CLLocation是否为负值,如果是这种情况,请不要使用lat / lon值。当您看到纬度/经度值为0/0时,很可能GPS没有确保位置锁定。

答案 1 :(得分:1)

这种情况正在发生,因为当您第一次启动应用时位置管理器会询问用户访问当前位置的权限以及用户何时允许 - 在获取当前位置并且您正在访问时,只需要很少的时间在完成该过程之前协调。

当您再次启动应用时位置管理器检测到您已经授予了权限,因此它可以非常快速地为您提供当前位置坐标。

所以解决方案是 - 你要等到它完成位置更新选择。您可以使用 dispatch 进行一些延迟,或者可以使用位置管理器委托方法 didUpdateUserLocation 或者如果您的UIViewController不是初始视图控制器 - 在这种情况下您应该实现此在AppDelegate中进行处理,在 didFinishLaunching 中使用您的代码,因此当您打开视图控制器时(无论您使用的是什么导航流程),位置详细信息都会在那里,因此位置管理员将跟踪您的位置。

希望它能帮到你!