How to request auth for CLLocationManager on macOS

I am writing an OSX application in Swift 3 that uses CLLocationManager, according to the docs and all the examples I found should be fine (this is a class that is 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 ) are not available for OSX. Currently, I have received calls to these functions 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 make this work on a MacOS desktop application?

+7
source share
2 answers

In accordance with the “Best Location Guidelines,” WWDC 2016 Session,

For macOS, we only support authorization. In addition, Core Location will automatically display a hint when you try to access location information.

You do not need to call requestAlwaysAuthorization on macOS.

Remember to turn on “Location” in the “Application Sandbox” settings for your purpose. In addition, in my tests, the invitation was displayed only at the first launch of the application.

+6
source

steps to run authorization request in OSX

1) set up a location manager with a delegate

 manager = CLLocationManager() manager.delegate = self 

2) implement the necessary delegate methods (they are marked as optional, but it is not!)

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

3) request location

 manager.requestLocation() 

All this. A popup saying “XXX would like to use your current location” will appear.

0
source

Source: https://habr.com/ru/post/1269665/


All Articles