Skip to content

Instantly share code, notes, and snippets.

@pimeo
Created June 17, 2016 16:43
Show Gist options
  • Save pimeo/2503f9c4035e883a007f46df4055afeb to your computer and use it in GitHub Desktop.
Save pimeo/2503f9c4035e883a007f46df4055afeb to your computer and use it in GitHub Desktop.
CLGeocoder reverseGeocodeLocation with timeout swift 2.0
//
// CLGeocoder+Timeout.swift
//
// Created by Bertrand Souriau on 17/06/2016.
// Thanks to Mathias Amnell (https://github.com/apping/APFoundation/blob/master/Pod/Classes/CLGeocoder%2BTimeout.m)
import Foundation
import MobileCoreServices
import CoreLocation
// https://github.com/apple/swift-evolution/blob/master/proposals/0088-libdispatch-for-swift3.md
extension CLGeocoder {
public func reverseGeocodeLocation(location: CLLocation, timeout: NSTimeInterval, completionHandler: CLGeocodeCompletionHandler) {
if( timeout <= 0 ) {
reverseGeocodeLocation(location, completionHandler: completionHandler)
return
}
var handled = false
reverseGeocodeLocation(location) { (placemarks:[CLPlacemark]?, error:NSError?) in
if( handled ) {
return
}
handled = true
completionHandler(placemarks, error)
}
let delay = dispatch_time(DISPATCH_TIME_NOW, Int64(timeout * Double(NSEC_PER_SEC)))
dispatch_after(delay, dispatch_get_main_queue()) {
if( handled ) {
return
}
handled = true
self.cancelGeocode()
completionHandler(nil, NSError(domain: kCLErrorDomain, code: CLError.GeocodeFoundNoResult.rawValue, userInfo: nil))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment