Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Could not get current Location from CLLocationManager

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading