您如何在SwiftUI中获得用户位置权限?
我尝试在点击按钮后询问用户位置权限,但是对话框大约一秒钟后消失。即使您最终还是及时单击它,权限仍然会被拒绝。
import CoreLocation
.
.
.
Button(action: {
let locationManager = CLLocationManager()
locationManager.requestAlwaysAuthorization()
locationManager.requestWhenInUseAuthorization()
}) {
Image("button_image")
}
诸如位置管理器之类的东西应该在您的模型中,而不是您的视图。
然后您可以在模型上调用一个函数以请求位置许可。
您现在正在做的问题是,关闭完成后,您的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
}
}
您可能还希望函数启动和停止位置更新以及@Published
CLLocation
属性
您只需要保留locationManager
。在这里,您去:
struct ContentView: View {
private let locationManager = CLLocationManager()
var body: some View {
Button(action: {
self.locationManager.requestAlwaysAuthorization()
self.locationManager.requestWhenInUseAuthorization()
}) {
Text("Request authorization")
}
}
}