0
votes

I am trying to simply get the user's current device location and store it in a global variable called userLoc. I have this code to call didUpdateLocation:

self.locationManager.requestLocation()
print("aaa ", self.userLoc)

and this to set the userLoc to the current location:

func locationManager(_ manager: CLLocationManager,
                         didUpdateLocations locations: [CLLocation]) {
        if let location = locations.last {
            self.userLoc = location
        }
    }

userLoc is defined like this:

var userLoc: CLLocation?

but when I run the app and try to print userLoc, it ALWAYS prints:

aaa nil

The Privacy - Location When In Use Usage Description is set in the Info.plist. I honestly dont know what else to try. I've been banging my head against the wall for a while trying to fix this. Any help you could give would be very much appreciate. Thank you.

1
Your print line is being called long before the location is updated. - rmaddy
How long does it usually take to update the location? I've thought that, but I've also tried putting in a sleep for a couple seconds to see if it gives it time to update. Nothing - Elliot Alderson
Do use sleep, especially from the main thread. Simply move your print to just after the line where you set self.userLoc. And also check the console for any messages related to missing privacy settings. And make sure you have a call to self.locationManager.requestWhenInUseAuthorization. There are many samples and tutorials on how to properly work with CoreLocation. - rmaddy
I've always ended up using locations.first ...not sure if that matters though. - arvidurs
When I do what you recommended, the userLoc prints, but when I try to reference userLoc it crashes becasue userLoc is still nil. And when I try the line self.locationManager.requestWhenInUseAuthorization i get an error: Expression resolves to an unused function - Elliot Alderson

1 Answers

0
votes

This is what I do to get user location within my view controller class. I think you are missing locationManager.startUpdatingLocation():

var currentLocation: CLLocationCoordinate2D!
var locationManager: CLLocationManager = CLLocationManager()

locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
currentLocation = locationManager.location!.coordinate