感谢Thomas的建议,我已根据原始请求修改了我的代码。我想知道我是不是想做一些不可能的事情,或者如果不是,我怎么能做到这一点。
如果用户未授权位置服务,我会通过带有“打开设置”按钮的提醒来提示他们,以更改应用的位置设置。这有效。但是从设置返回应用程序后,我想知道是否进行了更改并激活了位置服务。可以这样做吗?下面的闭包成功地让用户进入应用程序的设置,用户可以进行更改,用户可以返回,但是当用户按下“打开设置”时,即在设置更改之前,关闭会触发。顺便说一句:如果有更好的方法来处理用户批准应用程序当前未经授权的位置首选项,我会很感激建议。谢谢!
locationManager.requestWhenInUseAuthorization() // request authorization
let authStatus = CLLocationManager.authorizationStatus()
switch authStatus {
case .denied:
let alertController = UIAlertController(title: "Background Location Access Disabled", message: "In order to show the location weather forecast, please open this app's settings and set location access to 'While Using'.", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
alertController.addAction(UIAlertAction(title: "Open Settings", style: .`default`, handler: { action in
if #available(iOS 10.0, *) {
let settingsURL = URL(string: UIApplicationOpenSettingsURLString)!
UIApplication.shared.open(settingsURL, options: [:], completionHandler: {(success) in
print("*** Success closure fires")
let newAuthStatus = CLLocationManager.authorizationStatus()
switch newAuthStatus {
case .authorizedWhenInUse:
self.locationManager.startUpdatingLocation()
default:
print("Not .authorizedWhenInUse")
}
})
} else {
if let url = NSURL(string:UIApplicationOpenSettingsURLString) {
UIApplication.shared.openURL(url as URL)
}
}
}))
self.present(alertController, animated: true, completion: nil)
case .authorizedWhenInUse, .authorizedAlways:
locationManager.startUpdatingLocation()
case .restricted :
print("App is restricted, likely via parental controls.")
default:
print("UH!! WHAT OTHER CASES ARE THERE? ")
}