36

I use this code to check if I have access to the user location or not

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

And Xcode(12) yells at me with this warning:

'authorizationStatus()' was deprecated in iOS 14.0

So what is the replacement?

Rob
  • 415,655
  • 72
  • 787
  • 1,044
Ahmadreza
  • 6,950
  • 5
  • 50
  • 69

2 Answers2

92

It is now a property of CLLocationManager, authorizationStatus. So, create a CLLocationManager instance:

let manager = CLLocationManager()

Then you can access the property from there:

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

There are a few location related changes in iOS 14. See WWDC 2020 What's new in location.


Needless to say, if you also need to support iOS versions prior to 14, then just add the #available check, e.g.:

let authorizationStatus: CLAuthorizationStatus

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

switch authorizationStatus {
case .restricted, .denied:
    ...
default:
    ...
}
Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • 1
    Thanks but I'm getting this Static member 'manager' cannot be used on instance of type 'CLLocationManager' – Lukasz D Aug 15 '21 at 18:14
  • 1
    Bug in Xcode beta most likely if I set target to iOS 13 then both examples works using CLLocation literate as original poster and using let manager = CLLocationManager() as you demonstrated, there is no static member error then. Weird – Lukasz D Aug 18 '21 at 19:02
  • If you need to simultaneously support iOS 14 and earlier versions, use `#available` check. – Rob Sep 28 '21 at 00:36
0

Objective C Version:

In Class Interface

@property (nonatomic, strong) CLLocationManager *locationManager;

In Class Code

- (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...
KeithTheBiped
  • 832
  • 10
  • 21