Search code examples
iosswiftuicore-locationswiftui-map

How can I get user location with MapKit?


I write map app for iOS 17 with Xcode 15. And I have problem with detecting user location.

So, I add the parameters to info

info

And I create Map() with MapUserLocationButton()

var body: some View {
        Map(scope: mapScope){
            UserAnnotation()
        }
        .mapControls() {
            VStack {
                MapUserLocationButton(scope: mapScope)
                MapScaleView(scope: mapScope)
            }
        }
        .mapControlVisibility(Visibility.visible)
    }

And if I push MapUserLocationButton I got error: CLLocationManager(<CLLocationManager: 0x28377a500>) for <MKCoreLocationProvider: 0x280773210> did fail with error: Error Domain=kCLErrorDomain Code=1 "(null)"

I also tried to add:

 let locationManager = CLLocationManager()

.onAppear {
    locationManagerDidChangeAuthorization(locationManager)
}

func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
        switch manager.authorizationStatus {
        case .authorizedWhenInUse:  // Location services are available.
            enableLocationFeatures()
            break
            
        case .restricted, .denied:  // Location services currently unavailable.
            disableLocationFeatures()
            break
            
        case .notDetermined:        // Authorization not determined yet.
            manager.requestWhenInUseAuthorization()
            break
            
        default:
            break
        }
    }

but it didn't get result.

What I do wrong?


Console screenshot: Console screenshot


Solution

  • Please add these permissions to your .plist file

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
        <key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
        <string>YOUR MESSAGE</string>
        <key>NSLocationAlwaysUsageDescription</key>
        <string>YOUR MESSAGE</string>
        <key>NSLocationAlwaysAndWhenInUsageDescription</key>
        <string>YOUR MESSAGE</string>
        <key>NSLocationUsageDescription</key>
        <string>YOUR MESSAGE</string>
        <key>NSLocationWhenInUseUsageDescription</key>
        <string>YOUR MESSAGE</string>
    </dict>
    </plist>
    

    It is also recommended to use this delegate method to get exact errors.

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error)
    }
    

    enter image description here