Search code examples
ioscllocationmanagercllocationopenweathermap

Latidude and Longitude are incorrect first time app is launched ios


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

Solution

  • It's happening because when you launch your app first time Location manager asks for user permission to access current location and when user allows - It takes little time in process of fetching current location and you're accessing coordinates before completion of that process.

    When you launch your app again Location manager detects that you already gave the permission so it gives you current location coordinate very quickly.

    So the solution is - you've to wait until it completes location update opt. You can put some kinda delay there using dispatch OR can use Location manager delegate method didUpdateUserLocation OR if your UIViewController isn't the initial view controller - in this case you should implement this process in AppDelegate, use your code in didFinishLaunching, so when you'll open your view controller (whatever navigation flow you're using) location details will be there cause in meantime location manager will track your location.

    Hope it'll help you!