[英]Request permissions again after user denies location services?
我跟踪用户的位置并在我的负载首次加载时请求许可:
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
如果用户拒绝,但后来通过启用我的应用程序中的配置选项改变了主意,我该如何再次询问? 例如,我有一个用于自动检测用户位置的开关,所以当他们启用它时,我正在尝试这样做:
@IBAction func gpsChanged(sender: UISwitch) {
// Request permission for auto geolocation if applicable
if sender.on {
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
}
但是这段代码似乎没有做任何事情。 我希望它会再次询问用户是否要允许应用程序跟踪用户的位置。 这可能吗?
操作系统只会提示用户一次。 如果他们拒绝许可,就是这样。 您可以做的是通过将UIApplicationOpenSettingsURLString
传递给UIApplication
的openURL:
方法将用户定向到您的应用程序的设置。 如果他们愿意,他们可以从那里重新启用定位服务。 也就是说,您可能不应该过于激进地对他们进行窃听以获得许可。
权限弹窗只显示一次。 所以我们必须在那之后将用户重定向到设置。 下面是 Swift 中的代码:
import CoreLocation
// ...
@IBAction func userDidClickButton(_ sender: Any) {
// initialise a pop up for using later
let alertController = UIAlertController(title: "TITLE", message: "Please go to Settings and turn on the permissions", preferredStyle: .alert)
let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else {
return
}
if UIApplication.shared.canOpenURL(settingsUrl) {
UIApplication.shared.open(settingsUrl, completionHandler: { (success) in })
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
alertController.addAction(cancelAction)
alertController.addAction(settingsAction)
// check the permission status
switch(CLLocationManager.authorizationStatus()) {
case .authorizedAlways, .authorizedWhenInUse:
print("Authorize.")
// get the user location
case .notDetermined, .restricted, .denied:
// redirect the users to settings
self.present(alertController, animated: true, completion: nil)
}
}
你可以有一个替代的解决方案! 您可以使用更好的消息显示您自己的警报,这可以说服您的用户允许接收您的应用程序的推送通知。 如果用户允许,则只有您显示默认权限警报以启用推送通知,否则如果用户不允许,则实际上不显示默认警报,您可以将相应的标志保存在您的数据库或 NSUserDefaults 中,并且可以在以后一次又一次地询问用户您的应用程序中的一些事件。
你只有一次机会。 要让用户在拒绝权限后启用权限,他们必须通过“设置”应用程序。 请参阅在CLLocationManager中请求使用位置服务的权限。
我创建了包含用于通知的权限管理器的库,即使在用户拒绝权限后也会处理权限警报。
https://github.com/CrazyPro007/PermissionManager/tree/master/PermissionManager/PermissionManager
对于 Health Kit api。 开发人员可以简单地在readTypes Set<HKObjectType>
中添加另一个权限,用户将被重新提示允许权限。 我不完全确定这是否与位置服务相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.