CLLocationManager 的 AuthorizationStatus 在 iOS 14 上被弃用

AuthorizationStatus for CLLocationManager is deprecated on 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

那么替代品是什么?

现在是 CLLocationManagerauthorizationStatus 的 属性。因此,创建一个 CLLocationManager 实例:

let manager = CLLocationManager()

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

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

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


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

let authorizationStatus: CLAuthorizationStatus

if #available(iOS 14, *) {
    authorizationStatus = manager.authorizationStatus
} else {
    authorizationStatus = CLLocationManager.authorizationStatus()
}

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

Objective C版本:

在Class界面

@property (nonatomic, strong) CLLocationManager *locationManager;

在Class代码

- (id) init {
self = [super init];
if (self != nil) {
    self.locationManager = [[CLLocationManager alloc]init];
}
return self;
}

-(CLLocation*)getLocation
{
    CLAuthorizationStatus status = [self.locationManager authorizationStatus];
    if (status == kCLAuthorizationStatusNotDetermined)
    {
        [self promptToEnableLocationServices];
        return nil;
    }
 etc...