在 SwiftUI 中请求用户位置权限

yam*_*mbo 1 core-location user-permissions ios swift swiftui

你如何在 SwiftUI 中获得用户位置权限?

我尝试在点击按钮后请求用户位置权限,但对话框在大约一秒钟后消失。即使您最终及时点击它,权限仍然被拒绝。

import CoreLocation
.
.
.
Button(action: {
    let locationManager = CLLocationManager()
    locationManager.requestAlwaysAuthorization()
    locationManager.requestWhenInUseAuthorization()
}) {
    Image("button_image")
}
Run Code Online (Sandbox Code Playgroud)

Pau*_*w11 5

诸如位置管理器之类的东西应该在您的模型中,而不是您的视图中。

然后,您可以调用模型上的函数来请求位置权限。

你现在所做的问题是,CLLocationManager一旦关闭完成,你就会被释放。权限请求方法异步执行,因此关闭很快结束。

当位置管理器实例被释放时,权限对话框消失。

位置模型可能如下所示:

class LocationModel: NSObject, ObservableObject {
    private let locationManager = CLLocationManager()
    @Published var authorisationStatus: CLAuthorizationStatus = .notDetermined

    override init() {
        super.init()
        self.locationManager.delegate = self
    }

    public func requestAuthorisation(always: Bool = false) {
        if always {
            self.locationManager.requestAlwaysAuthorization()
        } else {
            self.locationManager.requestWhenInUseAuthorization()
        }
    }
}

extension LocationModel: CLLocationManagerDelegate {

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        self.authorisationStatus = status
    }
}
Run Code Online (Sandbox Code Playgroud)

您可能还需要函数来启动和停止位置更新和@Published CLLocation属性