Search code examples
iosswiftmapkitmkusertrackingmode

Required steps to show User Location in MapKit


I have a mapView embedded in a View Controller that I would like to show the user's location. While the following compiles, the map after loading does nothing and does not show the user's location. I tried the code first in viewDidLoad and then in viewDidFishingLoadingMap as I read that you need to let the map load first but it still does nothing.

Are there any additional steps beyond setting the tracking mode to get the map to center on the user's location? I have found various approaches in Objective-C using mapView.showsUserLocation = YES; or [self.mapView setCenterCoordinate:userLocation.location.coordinate animated:YES]; } but the following seems to be recommended for Swift.

func mapViewDidFinishLoadingMap(_ mapView: MKMapView){
        mapView.setUserTrackingMode(.follow, animated:true)
}

Solution

    • Enable user location with Interface Builder or code enter image description here
    • Add a Privacy - Location Always and When In Use Usage Description (or any other location usage mode you prefer) key to the info.plist file
    • Import CoreLocation
    • Check authorization status and prompt user if needed for location access.

    Swift

    if CLLocationManager.authorizationStatus() == .notDetermined {
        CLLocationManager().requestWhenInUseAuthorization()
    }
    

    Objective-c

    [CLLocationManager requestWhenInUseAuthorization];