iOS 请求始终授权仅在第一次显示权限警报

iOS Requesting Always Authorization Shows Permission Alert Just For the First Time

我第一次通过 xcode 在设备上安装我的 iOS 应用程序并且位置服务关闭时,requestAlwaysAuthorization() 显示 "Turn on location services" 将用户推送到设备设置以打开位置服务,然后用户返回应用程序并会看到 "permission" 警报(始终有三个选项,使用时和从不)。如果用户点击始终选项然后完全关闭应用程序并关闭位置服务然后再次打开应用程序,则不会显示 "Turn on location services" 警报。这是我的代码:

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 上进行测试,我不知道哪里出了问题。

您只需请求一次身份验证...如果用户授予权限,则您无需再次询问,如果他们拒绝,您将无法再次提示。如果被拒绝,您需要以不同的方式处理它。您将用户推送到设置菜单中的应用程序设置,用户必须从那里启用

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) 
        }
    }