Ios 仅在授予位置权限时打开SwiftUI视图

Ios 仅在授予位置权限时打开SwiftUI视图,ios,swift,swiftui,Ios,Swift,Swiftui,我有一个视图(比如V),其中用户回答了几个问题,并记录了他们的位置。然而,答案只有在用户的位置上才有意义 因此,我想要的是,当用户单击父视图上的按钮时,它会将他们带到V,并立即向他们请求位置权限。如果他们接受,他们可以继续回答问题,但如果他们拒绝,他们将导航回家长屏幕 我知道我可以使用self.presentation.wrappedValue.dismise()导航回父屏幕 但是,既然requestwhenUseAuthorization()是一个异步函数,我如何知道用户何时接受或拒绝了权限

我有一个视图(比如V),其中用户回答了几个问题,并记录了他们的位置。然而,答案只有在用户的位置上才有意义

因此,我想要的是,当用户单击父视图上的按钮时,它会将他们带到V,并立即向他们请求位置权限。如果他们接受,他们可以继续回答问题,但如果他们拒绝,他们将导航回家长屏幕

我知道我可以使用
self.presentation.wrappedValue.dismise()
导航回父屏幕

但是,既然
requestwhenUseAuthorization()
是一个异步函数,我如何知道用户何时接受或拒绝了权限

下面是关于使用Swift在iOS上获取用户位置的教程

my LocationService的代码:

导入核心位置
协议位置ServiceDelegate{
func didFetchCurrentLocation(location:地理位置)
func fetchCurrentLocationFailed(错误:error)
}
类LocationService:NSObject,CLLocationManagerDelegate{
让locationManager=CLLocationManager()
变量委托:LocationServiceDelegate
初始化(委托:LocationServiceDelegate){
self.delegate=委托
super.init()
self.setupLocationManager()
}
专用函数setupLocationManager(){
如果canUseLocationManager(){
locationManager.delegate=self
locationManager.desiredAccuracy=KCallocationAccuracyBest
}
}
func requestLocation(){
如果canUseLocationManager(){
打印(CLAuthorizationStatus.self)
locationManager.RequestWhenUseAuthorization()
locationManager.requestLocation()
}
}
func requestPermission(){
locationManager.RequestWhenUseAuthorization()
}
私有函数canUseLocationManager()->Bool{
返回CLLocationManager.locationServicesEnabled()
}
func locationManager(manager:CLLocationManager,didUpdateLocations位置:[CLLocation]){
打印(位置)
如果let location=locations.last{
让geoLocation=geoLocation(纬度:location.coordinate.lation,经度:location.coordinate.longitude)
delegate.didFetchCurrentLocation(地理位置)
}
}
func locationManager(manager:CLLocationManager,didFailWithError:error){
打印(错误)
delegate.fetchCurrentLocationFailed(错误:error)
}
脱硝{
locationManager.StopUpdatengLocation()
}
}
结构地理定位{
纬度:双
经度:双
}

CLLocationManagerDelegate
还有以下方法:

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
}

每次更改授权状态时都会调用此方法。我还建议您将
LocationService
作为
observeobject
实施,而不是使用委托方法

为什么
observateObject
方法会更好?因为SwiftUI中的
View
对象是一个
struct
,使用
struct
作为委托并不好,因为它是值类型。例如,您可以在这里阅读: