我目前正在尝试 CLLocation
,最近遇到了 authorizationStatus
。如果用户允许应用程序使用位置服务,我想显示一种 View ,如果他/她不允许,则显示另一种 View 。它按照我想要的方式工作,除了 .notDetermined
。如果我将其插入到我的 .denied
block 中并按“使用时允许”,我将无法呈现“允许”页面,而必须重新启动应用程序才能呈现它。如果我将其放入 .accesWhenInUse
block 中并按“拒绝”,情况也会相反。所以我的问题是,使用这个命令有什么好的做法?理想情况下,我希望应用程序等到用户实际做出选择并从那里加载它,但由于需要 .notDetermined
来处理,我有点迷失了。
到目前为止我的初始化位置函数:
private func initLocation() {
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
switch CLLocationManager.authorizationStatus() {
case .authorizedWhenInUse, .authorizedAlways :
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
break
case .notDetermined:
break
case .restricted, .denied:
print("well this is awkward..")
view.addSubview(noLocationTextView)
NSLayoutConstraint.activate([
noLocationTextView.heightAnchor.constraint(equalToConstant: 210),
noLocationTextView.widthAnchor.constraint(equalToConstant: 210),
noLocationTextView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
noLocationTextView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor)
])
noLocationTextView.text = "Well we're going to need your location"
break
}
}
}
我现在已将 .notDetermined
提取到其自己的案例中。
所以问题是,我该如何处理这个问题,以便应用程序在做出选择时等待并加载正确的 View ?
最佳答案
感谢@Paulw11,我设法使用 delegate method 解决了这个问题。因此,我没有使用我的 initLocation()
,而是使用了这个:
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .authorizedWhenInUse, .authorizedAlways:
goToLocationSettings.removeFromSuperview()
noLocationContainer.removeFromSuperview()
break
case .denied, .restricted:
print("well this is awkward..")
view.addSubview(noLocationContainer)
NSLayoutConstraint.activate([
noLocationContainer.heightAnchor.constraint(equalTo: self.view.heightAnchor),
noLocationContainer.widthAnchor.constraint(equalTo: self.view.widthAnchor),
])
noLocationContainer.insertSubview(goToLocationSettings, at: 3)
NSLayoutConstraint.activate([
goToLocationSettings.widthAnchor.constraint(equalToConstant: 300),
goToLocationSettings.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
goToLocationSettings.centerYAnchor.constraint(equalTo: self.view.centerYAnchor, constant: 200),
goToLocationSettings.heightAnchor.constraint(equalToConstant: 50)
])
break
default:
break
}
}
这样 .notDetermined
是 default
,它不会执行任何操作,直到用户按照我的意愿做出选择。它也会实时变化,因此如果我拒绝对位置的访问,然后在应用程序运行时授予它,它只会更新 View 并显示内容。希望这可以帮助遇到类似问题的人!
关于ios - .notDetermined 等待用户的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51709386/