斯威夫特,
禁用应用的位置服务后,位置管理器委托方法将开始显示错误。因此,在收到错误消息后,我们可以检查是否启用/禁用了位置服务。根据结果,我们可以要求用户进行设置并打开位置服务。
在错误的位置管理器委托方法中,添加位置权限检查
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {
self.checkLocationPermission()
}
}
位置权限检查代码
func checkLocationPermission() {
if CLLocationManager.locationServicesEnabled() {
switch(CLLocationManager.authorizationStatus()) {
case .notDetermined, .restricted, .denied:
openSettingApp(message:NSLocalizedString("please.enable.location.services.to.continue.using.the.app", comment: ""))
case .authorizedAlways, .authorizedWhenInUse:
print("Access")
}
} else {
print("Location services are not enabled")
openSettingApp(message:NSLocalizedString("please.enable.location.services.to.continue.using.the.app", comment: ""))
}
}
开启设定应用程式的程式码,
func openSettingApp(message: String) {
let alertController = UIAlertController (title: APP_NAME_TITLE, message:message , preferredStyle: .alert)
let settingsAction = UIAlertAction(title: NSLocalizedString("settings", comment: ""), style: .default) { (_) -> Void in
guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else {
return
}
if UIApplication.shared.canOpenURL(settingsUrl) {
UIApplication.shared.open(settingsUrl, options: [:], completionHandler: nil)
}
}
alertController.addAction(settingsAction)
let cancelAction = UIAlertAction(title: NSLocalizedString("cancel", comment: ""), style: .default, handler: nil)
alertController.addAction(cancelAction)
present(alertController, animated: true, completion: nil)
}