Home > Net >  Could not get current Location from CLLocationManager
Could not get current Location from CLLocationManager

Time:10-04

class LocationManager: NSObject, CLLocationManagerDelegate {
    
    private var onLocation: ((CLLocationCoordinate2D) -> Void)?
    private let manager: CLLocationManager
    
    override init() {
        manager = CLLocationManager()
        super.init()
        
        manager.desiredAccuracy = kCLLocationAccuracyBest
        manager.requestWhenInUseAuthorization()
        
        manager.delegate = self
        manager.startUpdatingLocation()
        
    }
    
    public func getLocation(_ onLocation: ((CLLocationCoordinate2D) -> Void)?) {
        self.onLocation = onLocation
    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        print(#function, locations)
        guard let currentCoordinate = manager.location?.coordinate else {return}
        onLocation?(currentCoordinate)
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(#function, error)
    }
    
}

this code is not calling didUpdateLocation or didFailWithError. can anyone tell me what could be the problem here?

LocationManager().getLocation { coordinate in
    print(#function, coordinate)
}

this is how i am calling it.

CodePudding user response:

You need to retain the let manager = CLLocationManager() in your class as a property. Otherwise, it will be deallocated at the end of that function and hence none of its delegate methods will be called at all.

UPDATED

Another issue is the following code where you call getLocation. You need to retain LocationManager() in your client class otherwise the LocationManager will be deallocated at the end of that function.

private let locationManager = LocationManager()

locationManager.getLocation { coordinate in
    print(#function, coordinate)
}
  • Related