【问题标题】:AuthorizationStatus for CLLocationManager is deprecated on iOS 14CLLocationManager 的 AuthorizationStatus 在 iOS 14 上已弃用
【发布时间】:2021-01-12 08:40:44
【问题描述】:

我使用此代码检查我是否可以访问用户位置

if CLLocationManager.locationServicesEnabled() {
    switch CLLocationManager.authorizationStatus() {
        case .restricted, .denied:
            hasPermission = false
        default:
            hasPermission = true
        }
    } else {
        print("Location services are not enabled")
    }
}

Xcode(12) 用这个警告对我大喊:

'authorizationStatus()' was deprecated in iOS 14.0

那么替换是什么?

【问题讨论】:

    标签: ios swift core-location ios14


    【解决方案1】:

    它现在是CLLocationManagerauthorizationStatus 的属性。所以,创建一个CLLocationManager 实例:

    let manager = CLLocationManager()
    

    然后您可以从那里访问该属性:

    switch manager.authorizationStatus {
    case .restricted, .denied:
        ...
    default:
        ...
    }
    

    iOS 14 中有一些与位置相关的更改。请参阅 WWDC 2020 What's new in location


    不用说,如果您还需要支持14之前的iOS版本,那么只需添加#available检查,例如:

    let authorizationStatus: CLAuthorizationStatus
    
    if #available(iOS 14, *) {
        authorizationStatus = manager.authorizationStatus
    } else {
        authorizationStatus = CLLocationManager.authorizationStatus()
    }
    
    switch authorizationStatus {
    case .restricted, .denied:
        ...
    default:
        ...
    }
    

    【讨论】:

    • 谢谢,但我得到这个静态成员 'manager' 不能用于类型为 'CLLocationManager' 的实例
    • 如果我将目标设置为 iOS 13,则最有可能在 Xcode beta 中出现错误,那么这两个示例都使用 CLLocation literate 作为原始海报并使用 let manager = CLLocationManager() 如您所演示的那样,没有静态成员错误.奇怪
    • 如果需要同时支持iOS 14及更早版本,请使用#available检查。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多