swift CLLocationManager的AuthorizationStatus在iOS 14上已弃用

uujelgoq  于 2023-10-15  发布在  Swift
关注(0)|答案(3)|浏览(198)

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

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

那么,什么是替代品?

vi4fp9gy

vi4fp9gy1#

它现在是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:
    ...
}
brccelvz

brccelvz2#

目标C版本:
类内接口

@property (nonatomic, strong) CLLocationManager *locationManager;

在类代码中

- (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...
ubof19bj

ubof19bj3#

只需移动点前的括号:

CLLocationManager().authorizationStatus

相关问题