Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CLGeocoder how to set Timeout?

I am trying to define city name by CLLocation structure with reverse... method request to CLGeocoder object, but I don't know how to set timeout? If there are no internet connection request time may take about 30 seconds - it is too long...

like image 947
Rasim Avatar asked Oct 18 '13 07:10

Rasim


2 Answers

There isn't any built in functionality to handle this that I'm aware of. I've started using the following solution. Apologies it's in Swift, I don't speak fluent Objective-C.

This will give you a 2 second timeout

func myLookupFunction(location: CLLocation)
{
    let timer = NSTimer(timeInterval: 2, target: self, selector: "timeout:", userInfo: nil, repeats: false);
     geocoder.reverseGeocodeLocation(location){
        (placemarks, error) in
        if(error != nil){
          //execute your error handling
        }
        else
        {
          //execute your happy path
        }
    }
    NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSDefaultRunLoopMode)
}

func timeout(timer: NSTimer)
{
    if(self.geocoder.geocoding)
    {
        geocoder.cancelGeocode();
    }
}

After the timeout fires, your callback will be executed and the error path with be called.

You'll get an error with the details:

  • Code = 10
  • Localised Description(English) = The operation couldn’t be completed. (kCLErrorDomain error 10.)

Hope this helps.

like image 108
JTango18 Avatar answered Oct 18 '22 21:10

JTango18


@JTango18 answer in Swift 3:

func myLookupFunction(location: CLLocation)
{
    let timer = Timer(timeInterval: 2, target: self, selector: #selector(self.timeout), userInfo: nil, repeats: false);
    geocoder.reverseGeocodeLocation(location){
        (placemarks, error) in
        if(error != nil){
            //execute your error handling
        }
        else
        {
            //execute your happy path
        }
    }
    RunLoop.current.add(timer, forMode: RunLoopMode.defaultRunLoopMode)
}

func timeout()
{
    if (geocoder.isGeocoding){
        geocoder.cancelGeocode()
    }
}
like image 30
YYamil Avatar answered Oct 18 '22 21:10

YYamil