how to request auth for CLLocationManager on macOS

Viewed 1372

I'm writing an OSX app in swift 3 that uses CLLocationManager, according to the docs and all the examples I've found the following should be fine (this is in a class that that is a CLLocationManagerDelegate)

if CLLocationManager.locationServicesEnabled() {
    let lm = CLLocationManager()            
    lm.requestWhenInUseAuthorization()            
    lm.delegate = self
    lm.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
    lm.startUpdatingLocation()
    print("should start getting location data")
} else {
    print("Location service disabled");
}

but it seems requestWhenInUseAuthorization (and requestAlwaysAuthorization) aren't available to OSX. I've currently got those function calls wrapped in #if blocks:

#if os(macOS)
    // can't find way for MacOSX to request auth
#endif

#if os(watchOS) || os(tvOS)
    lm.requestWhenInUseAuthorization()
#endif

 #if os(iOS)
    lm.requestAlwaysAuthorization()
 #endif

So does anyone know how to get this working in a macOS desktop application?

2 Answers

According to the Core Location Best Practices WWDC 2016 session,

For macOS, we only support always authorization. Furthermore, Core Location will automatically display a prompt when you attempt to access location information.

You don't need to call requestAlwaysAuthorization on macOS.

Don't forget to turn on "Location" under the "App Sandbox" capability for your target. Also, in my tests, the prompt was only shown the first time the app was run.

steps to trigger the auth request in OSX

1) set up location manager with delegate

manager = CLLocationManager()
manager.delegate = self

2) implement required delegate methods (these are marked optional, but they're not!)

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    //Do Stuff
}

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    //Error
}

3) request the location

manager.requestLocation()

That's all. The 'XXX Would like to use your current location' popup will now appear

Related