iOS 14中CLLocationManager的AuthorizationStatus已废弃

41

我使用这段代码来检查我是否有访问用户位置的权限

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

那么替代品是什么?

3个回答

97

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

let manager = CLLocationManager()

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

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

iOS 14有一些与位置相关的变化,请参见WWDC 2020中的位置更新


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

let authorizationStatus: CLAuthorizationStatus

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

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

1
谢谢,但我得到了这个错误:静态成员“manager”无法在类型为“CLLocationManager”的实例上使用。 - Lukasz D
1
如果我将目标设置为iOS 13,则Xcode beta中可能存在错误,使用CLLocation字面量作为原始帖子和使用您演示的let manager = CLLocationManager(),则两个示例均可以正常工作,此时不会出现静态成员错误。奇怪。 - Lukasz D
如果您需要同时支持iOS 14及以下版本,请使用#available检查。 - Rob

0

Objective 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...

0
只需将括号移到句点之前即可:
CLLocationManager().authorizationStatus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接