0

I want to get the user location, that's what I did: I set locationManager in my ViewController:

var locationManager = CLLocationManager()

func setUpLocationManager() {
    locationManager.delegate = self
    locationManager.distanceFilter = 5
    locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
    mapView?.showsUserLocation = true
    locationManager.startUpdatingLocation()
}

Here is the function that is called once the location is updated:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if !locations.isEmpty {
            print("\(locations[0])")
        }
    }
}

It prints the initial location of the user position (see image), but I consider it wrong, because it an approximation. I also tried with:

func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
    let accuracy = userLocation.location?.horizontalAccuracy
    if accuracy == locationManager.desiredAccuracy {
        print("\(locations[0])")
    }
}

But it never prints the location because locationManager.desiredAccuracy is equal to -2 and accuracy is always > 0.

This what I see on the mapView:

enter image description here enter image description here

Initially the user pin shows a position near to the real position (but it is not right), subsequently the user pin moves to the real user position. I want the function didUpdateLocations to be called when the user pin is on the right position. My question is similar to this, but it was in objective-c.

Any hints? Thanks

Nick
  • 875
  • 6
  • 20
Edoardo
  • 657
  • 7
  • 24

1 Answers1

1

ref. MKMapView's user location is wrong on startup or resume

Swift version:

func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
    let accuracy = userLocation.location?.horizontalAccuracy
    if accuracy ... {

    }
}
Kosuke Ogawa
  • 7,383
  • 3
  • 31
  • 52
  • Thanks, but I don't understand what to enter inside the if condition, because if I compare it with locationManager.desiredAccuracy it always returns false because desiredAccuracy is equal to -2. – Edoardo Dec 10 '19 at 15:24