Swift:locationManager.authorizationStatus 保持在 .notDetermined - 没有显示用户面对的请求

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

我正在尝试在 SwiftUI 中实现一个应用程序,我需要设备位置。我无法获得用户的授权 - 没有显示请求对话框。 authorizationStatus 始终返回 .notDetermined。我错过了什么?

class LocationViewModel: NSObject, ObservableObject, CLLocationManagerDelegate {
    private var locationManager = CLLocationManager()

    override init() {
        super.init()
        self.locationManager.delegate = self
        
        switch locationManager.authorizationStatus {
            case .authorizedAlways: self.locationManager.startUpdatingLocation()
            case .notDetermined: self.locationManager.requestWhenInUseAuthorization()
            case .denied, .restricted: print("denied")
            break
            default: break
        }
    }

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

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("Location Manager failed with error: \(error)")
    }
}

我将“隐私 - 位置始终使用说明”添加到 info.plist 中。还需要补充吗?

ios swift core-location
1个回答
0
投票

尝试将 NSLocationWhenInUseUsageDescription 添加到 info.plist。 您是否始终需要位置或仅在前台使用应用程序时需要?

© www.soinside.com 2019 - 2024. All rights reserved.