Ios 在SwiftUI中请求用户位置权限
如何在SwiftUI中获得用户位置权限 我试着在点击按钮后询问用户位置权限,但大约一秒钟后对话框消失了。即使您最终及时单击了它,权限仍然被拒绝Ios 在SwiftUI中请求用户位置权限,ios,swift,swiftui,core-location,user-permissions,Ios,Swift,Swiftui,Core Location,User Permissions,如何在SwiftUI中获得用户位置权限 我试着在点击按钮后询问用户位置权限,但大约一秒钟后对话框消失了。即使您最终及时单击了它,权限仍然被拒绝 import CoreLocation . . . Button(action: { let locationManager = CLLocationManager() locationManager.requestAlwaysAuthorization() locationManager.requestWhenInUseAuth
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属性(如位置管理器)应该在您的模型中,而不是视图中 然后可以在模型上调用函数以请求位置权限 您现在所做的问题是,一旦完成关闭,您的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")
}
}
}
您只需要保留locationManager。给你:
struct ContentView: View {
private let locationManager = CLLocationManager()
var body: some View {
Button(action: {
self.locationManager.requestAlwaysAuthorization()
self.locationManager.requestWhenInUseAuthorization()
}) {
Text("Request authorization")
}
}
}
我如何构造一个模型类以获得您描述的位置?我如何构造一个模型类以获得您描述的位置?