jamesdamico
jamesdamico

Reputation: 9

Swift - Location Manager not available right away

So basically when the app loads it's supposed to center the map on the user location, but sometimes will get stuck at the guard let. Here is the code:

override func viewDidLoad() {
    super.viewDidLoad()
    mapView.delegate = self
    locationManager.delegate = self
    configureLocationServices()
    addDoubleTap()
}


//Center map around user location
func centerMapOnUserLocation(){
    print("In \(#function)")
    guard let coordinate = locationManager.location?.coordinate else { print("Error getting coordinate"); return}


    let coordinateRegion = MKCoordinateRegion.init(center: coordinate, latitudinalMeters: locationZoomRadius, longitudinalMeters: locationZoomRadius)
    mapView.setRegion(coordinateRegion, animated: true)

    //Setting local latitude and longitude variables to current location
    latitude = "\(coordinate.latitude)"
    longitude = "\(coordinate.longitude)"
    previewDataOnButton()
    print("Centered Map")
}

// MARK: - Location Services

//Request to enable location services
func configureLocationServices(){
    if authorizationStatus == .notDetermined{
        locationManager.requestAlwaysAuthorization()
    } else {
        return
    }
}

//If authorization changes then call centerMapOnUserLocation
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    print("Authorization changed in \(#function). Calling centerMapOnUserLocation")
    centerMapOnUserLocation()
}

}

It seems to get stuck at the guard let in centerMapOnUserLocation(). This is shown through print statements:

Authorization changed in locationManager(_:didChangeAuthorization:). Calling centerMapOnUserLocation

In centerMapOnUserLocation()

Error getting coordinate

Im not sure how to fix this. Like I said sometimes it passes by the guard let and sometimes it gets stuck.

Upvotes: 0

Views: 396

Answers (1)

Frankenstein
Frankenstein

Reputation: 16361

In you viewDidLoad add this line:

locationManager.startUpdatingLocation()

Then use this CLLocationManagerDelegate method:

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

You could pass in the locations into your method and move guard let before passing the location like this:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    guard let location = locations.last else { return }
    centerMapOnUserLocation(location: location.last)
}

Upvotes: 0

Related Questions