Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS and Swift: CLLocationManagerDelegate not updating location coordinates beyond the first location

Using the following code, my currentLat and currentLong are not updating beyond the first location. locations never has more than 1 item, and it's always exactly the same.

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let loc: CLLocation = locations[locations.count - 1]
    currentLat = loc.coordinate.latitude
    currentLong = loc.coordinate.longitude
}

All the searching I've been doing has only shown how to get it to work if it doesn't work at all, but this DOES work, but only once.

The way I expect this to work is to continuously update the GPS coordinates and fire this delegate off whenever the location is updated. Does the location keep updating the entire time? I thought it would due to the terminology of "startUpdatingLocation()" and there being a "stopUpdatingLocation()." Am I trying to use this incorrectly?

Like I said, it works for the first time, so it's loaded and started just fine, the permissions are allowed, the info.plist has the necessary entries.

like image 312
sdouble Avatar asked Nov 16 '25 11:11

sdouble


1 Answers

When you want to update your location, you should stop existing update once it got new location. You can use stopUpdatingLocation() in your didUpdateLocations: method to do so.

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    // This should match your CLLocationManager()
    locManager.stopUpdatingLocation()

    let loc: CLLocation = locations[locations.count - 1]
    currentLat = loc.coordinate.latitude
    currentLong = loc.coordinate.longitude
}

Then call your locManager.startUpdatingLocation() when you need new location.

like image 96
Brian Nezhad Avatar answered Nov 18 '25 07:11

Brian Nezhad