I have a separate class named LocationService
class LocationService: NSObject, CLLocationManagerDelegate {
private var locationManager = CLLocationManager()
private var locationCallback: ((CLLocation?) -> Void)!
override init(){
super.init()
self.locationManager.delegate = self
}
public func getCurrentLocation (_ completion: @escaping(CLLocation?) -> Void) {
if PermissionManager.hasLocationPermission() && CLLocationManager.locationServicesEnabled() {
self.locationCallback = completion
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.startUpdatingLocation()
} else {
completion(nil)
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("LOCATIONS: ", locations)
locationCallback(locations.first)
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("LOCATION ERROR: ", error)
locationCallback(nil)
}
func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!) {
print("LOCATION: ", newLocation)
locationCallback(newLocation)
}
deinit {
print("DEINIT LOCATION SERVICE")
}
}
If I trigger getCurrentLocation
, none of the location manager delegate functions were called, although startUpdatingLocation
was reached.
I have no view controller because it’s inside a react native plugin.
The Location When In Use Usage Description is set in the info.plist and the deinit function was never called.
Furthermore, the location permission is also granted.
Does someone know what is missing?
2
Answers
First you must ask permission from user
self.locationManager.requestWhenInUseAuthorization()
This is extension
maybe you must use this:
static let shared = LocationManager()
when I want location , I use:
LocationManager.shared.request()
this works for me