首页 > 解决方案 > CLLocationManager 的 AuthorizationStatus 在 iOS 14 上已弃用

问题描述

我使用此代码检查我是否有权访问用户位置

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

那么替代品是什么呢?

标签: iosswiftcore-locationios14

解决方案


它现在是CLLocationManager,的一个属性authorizationStatus。所以,创建一个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:
    ...
}

推荐阅读