Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Location without internet connection

I want to get the location of the user when press a button, I found a way to do that with CLLocationManager, that code work perfectly until the device the device doesn't have network connection, the function func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) catch an error

((NSError?) error = domain: "kCLErrorDomain" - code: 2 { _userInfo = nil })

How can I get the device location without internet connection? here is the code I use

import CoreLocation

class SesionViewController: UIViewController, CLLocationManagerDelegate {

    let locationManager =  CLLocationManager()

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: { (placemarks, error) -> Void in
            if (error != nil) {
                print("Error:" + error!.localizedDescription)
                return
            }
            if placemarks!.count > 0 {
                let pm = placemarks![0] as CLPlacemark
                print(pm!.coordinate.latitude)
            }else {
                print("Error with data")
            }

        })
    }
func startButtonPress(sender:UIButton!){
        self.locationManager.delegate = self
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locationManager.requestWhenInUseAuthorization()
        self.locationManager.startUpdatingLocation()
        self.locationManager.stopUpdatingLocation()
    }
}

Edit

I already found the solution, I just don't execute CLGeocoder().reverseGeocodeLocation... just catch the location with the locations var like this

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    print(manager.location!.coordinate.latitude)
}
like image 857
Kristian Sthefan Cortes Prieto Avatar asked May 21 '26 19:05

Kristian Sthefan Cortes Prieto


1 Answers

from Apple doc about ClGeocoder

The computer or device must have access to the network in order for the geocoder object to return detailed placemark information

CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: { (placemarks, error) -> Void in
            if (error != nil) {
                print("Error:" + error!.localizedDescription)
                return
            }
            if placemarks!.count > 0 {
                let pm = placemarks![0] as CLPlacemark
                print(pm!.coordinate.latitude)
            }else {
                print("Error with data")
            }

        })

will always report an error without an internet access. Your location data are still available (if your device has GPS unit)

like image 73
user3441734 Avatar answered May 23 '26 11:05

user3441734



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!