如果应用程序的隐私访问位置被拒绝怎么办?
晚上伙计们,我正在编写一个在使用时使用位置的简单应用程序.
设计模式
>在所有内容之前,当您启动应用程序时,它将检查是否已设置权限.
>如果不是,则显示要求许可的警报.
>如果是并且被授予,它将继续完成其工作.
>如果是并拒绝,则会显示一条警报,要求使用指向设置的按钮授予访问权限.
>应该可以从设置返回到应用程序.
>应用程序完成其工作.
>如果用户在应用程序仍处于打开状态时更改隐私设置,则应通知应用程序,并重复编号1.
守则到目前为止
MainController
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)
}
的LocationManager
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?
使用此设置我遇到此错误:警告:尝试呈现< UIAlertController:0x145ae7ee0> on< xxx.xxController:0x143e04720>其视图不在窗口层次结构中!
>如何编写指向设置的设置按钮?
>我如何编码:“从设置页面,我可以返回应用程序”?
最佳答案 >首次访问self.view属性后调用viewDidLoad.这意味着在窗口层次结构上添加此self.view之后,首先称为viewDidLoad.将检查代码移动到viewDidAppear(_ :)函数并确保显示视图控制器.
>打开设置应用程序的代码似乎没问题,但不要忘记检查它可用的系统版本.
>当您的应用处于后台状态时,您的应用无法以某种方式与其他应用互动.