The User is on a map view. When doing a long press somewhere on the map the following function gets triggered to set a new annotation inclusively a proper title.
func action(gestureRecognizer: UIGestureRecognizer) {
if gestureRecognizer.state == UIGestureRecognizerState.Began {
var newTouch: CGPoint = gestureRecognizer.locationInView(self.mapView)
var newCoordinate: CLLocationCoordinate2D = mapView.convertPoint(newTouch, toCoordinateFromView: self.mapView)
var newLocation = CLLocation(latitude: newCoordinate.latitude, longitude: newCoordinate.longitude)
var newAnnotation = MKPointAnnotation()
newAnnotation.coordinate = newCoordinate
CLGeocoder().reverseGeocodeLocation(newLocation, completionHandler: {(placemarks, error) in
if error != nil { println(error) }
let p: CLPlacemark = placemarks[0] as CLPlacemark
var thoroughfare: String? = p.thoroughfare
var subThoroughfare: String? = p.subThoroughfare
if p.thoroughfare == nil || p.subThoroughfare == nil {
var date = NSDate()
newAnnotation.title = "Added \(date)"
} else {
newAnnotation.title = thoroughfare! + " " + subThoroughfare!
}
})
self.mapView.addAnnotation(newAnnotation)
self.mapView.selectAnnotation(newAnnotation, animated: true)
places.append(["name":"\(newAnnotation.title)", "lat":"\(newCoordinate.latitude)", "lon":"\(newCoordinate.longitude)"])
}
}
I know it is working fine when keeping the last three lines of code within the CLGeocoder block (closure?). But if I separate those and list them after the }) (or put some of the code to another thread) I'm facing the problem that its running asynchronous (as I don't understand how to control async vs sync) and by the time the annotation is added to the map and saved to places its title is not set yet by the CLGeocoder.
A beginner to programming is asking: What would be necessary to be implemented (disptach_sync...-something) so the last lines of code wait for the CLGeocoder block to finish? I haven't managed to implement this command in the right way yet...