如何使用MapKit获取用户位置?

问题描述 投票:0回答:1

我使用 Xcode 15 为 iOS 17 编写地图应用程序。我在检测用户位置时遇到问题。

所以,我将参数添加到info

我用 MapUserLocationButton() 创建 Map()

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

如果我按下 MapUserLocationButton 我收到错误:

CLLocationManager(<CLLocationManager: 0x28377a500>) for <MKCoreLocationProvider: 0x280773210> did fail with error: Error Domain=kCLErrorDomain Code=1 "(null)"

我还尝试添加:

 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
        }
    }

但没有得到结果。

我做错了什么?请帮忙。


控制台截图:

swift mapkit xcode15 ios17
1个回答
0
投票

请将这些权限添加到您的

.plist
文件中

<?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>Privacy — Location When in Usage Description</key>
    <string>YOUR MESSAGE</string>
    <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>

还建议使用此

delegate
方法来获得准确的错误。

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error)
 }
© www.soinside.com 2019 - 2024. All rights reserved.