当我通过xcode在设备上安装iOS应用并且关闭位置服务时,requestAlwaysAuthorization()第一次显示“打开位置服务”,该按钮将用户推送到设备设置以打开位置服务,然后用户返回应用程序,并且会看到“权限”警报(始终使用三个选项,使用时从不使用)。如果用户点击始终选项,然后完全关闭应用程序并关闭位置服务,然后再次打开应用程序,则不会显示“打开位置服务”警报。这是我的代码:
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
NotificationCenter.default.addObserver(self, selector: #selector(checkLocationService), name: Notification.Name.UIApplicationWillEnterForeground, object: nil)
}
@objc func checkLocationService() {
if CLLocationManager.locationServicesEnabled() {
switch CLLocationManager.authorizationStatus() {
case .denied, .notDetermined, .restricted:
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
case .authorizedWhenInUse, .authorizedAlways:
...
}
} else {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
}
}
我已经在Info.plist中添加了所有三个位置键:
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>My app need your location to work</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>My app need your location to work</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>My app need your location to work</string>
我正在iOS 11和12上进行测试,不知道出了什么问题。
答案 0 :(得分:1)
您只需要请求一次身份验证...如果用户授予了权限,则您无需再次询问,如果他们拒绝,您将无法再次提示。如果遭到拒绝,您需要采取不同的处理方式。您将用户推送到设置菜单中的应用设置,用户必须从那里启用
switch CLLocationManager.authorizationStatus() {
case .notDetermined, .restricted:
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
case .authorizedWhenInUse, .authorizedAlways:
...
case .denied:
// present an alert advising the user that they need to go to the settings menu to enable the permissions as they have previously denied it.
// if the user presses Open Settings on the alert....
if let url = URL(string: UIApplicationOpenSettingsURLString) {
UIApplication.shared.open(url: url)
}
}