【发布时间】:2017-03-02 05:31:02
【问题描述】:
如果应用的位置隐私访问被拒绝怎么办?
晚上好,我正在编写一个简单的应用程序,该应用程序在使用时使用位置。
设计模式
-
在一切之前,当你启动应用程序时,它会检查是否已经设置了权限。
- 如果没有,它会显示一条请求许可的警报。
- 如果是并获得批准,它会继续工作。
- 如果是并且被拒绝,它会显示一条警报,要求通过指向设置的按钮授予访问权限。
- 应该可以从设置返回到应用程序。
应用程序完成了它的工作。
- 如果用户在应用仍处于打开状态时更改隐私设置,应通知应用,并重复第 1 条。
到目前为止的代码
主控制器
let manager = LocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// ...
if manager.getPermission() == false {
//show alert
showAcessDeniedAlert()
}
manager.onLocationFix = {
//This is a function used for a closure
}
}
}
func showAcessDeniedAlert() {
let alertController = UIAlertController(title: "Location Accees Requested",
message: "The location permission was not authorized. Please enable it in Settings to continue.",
preferredStyle: .alert)
let settingsAction = UIAlertAction(title: "Settings", style: .default) { (alertAction) in
// THIS IS WHERE THE MAGIC HAPPENS!!!!
if let appSettings = URL(string: UIApplicationOpenSettingsURLString) {
UIApplication.shared.open(appSettings as URL)
}
}
alertController.addAction(settingsAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(cancelAction)
present(alertController, animated: true, completion: nil)
}
位置管理器
import CoreLocation
extension Coordinate {
init(location: CLLocation) {
latitude = location.coordinate.latitude
longitude = location.coordinate.longitude
}
}
final class LocationManager: NSObject, CLLocationManagerDelegate {
let manager = CLLocationManager()
var onLocationFix: ((Coordinate) -> Void)?
override init() {
super.init()
manager.delegate = self
manager.requestLocation()
}
func getPermission() -> Bool {
switch CLLocationManager.authorizationStatus() {
case .authorizedAlways:
return true
case .authorizedWhenInUse:
return true
case .denied:
return false
case .restricted:
return false
case .notDetermined:
manager.requestWhenInUseAuthorization()
return getPermission()
}
}
//MARK: CLLocationManagerDelegate
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedWhenInUse {
manager.requestLocation()
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error.localizedDescription)
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.first else { return }
let coordinate = Coordinate(location: location)
if let onLocationFix = onLocationFix {
onLocationFix(coordinate)
}
}
}
我该怎么办?
-
如果隐私被拒绝,我如何显示 AlertController?
使用此设置我遇到此错误:
Warning: Attempt to present <UIAlertController: 0x145ae7ee0> on <xxx.xxController: 0x143e04720> whose view is not in the window hierarchy!。 如何编码指向设置的设置按钮?
如何编码:“从设置页面,我可以返回应用程序”?
【问题讨论】:
标签: swift location core-location privacy