繁体   English   中英

应用程序仅在使用时请求位置访问

[英]app only requesting location acces when in use

我想使用 requestAlwaysAuthorization 但由于某种原因,它只提供允许一次、使用时允许或不允许的选项。 这是我的代码。

    if CLLocationManager.locationServicesEnabled() {
        switch locationManager.authorizationStatus {
            case .notDetermined, .restricted, .denied:
                locationManager.requestAlwaysAuthorization()
        case .authorizedAlways:
            break
        case .authorizedWhenInUse:
        locationManager.requestAlwaysAuthorization()
            @unknown default:
            break
        }
        } else {
            locationManager.requestAlwaysAuthorization()

来自 Apple 的requestAlwaysAuthorization文档:

您必须先调用此方法或 requestWhenInUseAuthorization() 方法,然后您的应用才能接收位置信息。 要调用此方法,您必须在应用的 Info.plist 文件中同时拥有 NSLocationAlwaysUsageDescription 和 NSLocationWhenInUseUsageDescription 键 当当前授权 state 是以下任一情况时,您可以调用 requestAlwaysAuthorization():

未确定 - CLAuthorizationStatus.notDetermined

使用时 — CLAuthorizationStatus.authorizedWhenInUse

当用户做出权限选择时,使用 CLLocationManager 委托上的 locationManager(_:didUpdateLocations:) 方法接收更新。

核心位置限制对 requestAlwaysAuthorization() 的调用。 在您的应用调用此方法后,进一步调用无效

基于此,您的代码几乎没有问题。

  1. requestAlwaysAuthorization的调用过多。 这应该足够了:
if CLLocationManager.locationServicesEnabled() {
     switch locationManager.authorizationStatus {
     case .notDetermined, .authorizedWhenInUse:
             locationManager.requestAlwaysAuthorization()
     default:
        print("Cannot ask user for requestAlwaysAuthorization")
     }
}

当用户已经拒绝位置权限时,再次请求将不会显示弹出窗口。

  1. Info.plist缺少NSLocationAlwaysUsageDescriptionNSLocationWhenInUseUsageDescription 在 Info.plist 中为这些定义非空字符串。

  2. 最后尝试在设备/模拟器上重新安装应用程序以清除先前授予或拒绝的位置权限

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM