In using CLGeocoder I get a crash (EXC_BAD_ACCESS) right after the let placemark ... in the closure success part which I don't understand. I am testing and may have made tried to access the server many times. Or do I need to make the call in a background thread?
import UIKit
import CoreLocation
class ViewController: UIViewController {
var destinationPlacemark = CLPlacemark()
override func viewDidLoad() {
super.viewDidLoad()
forwardGeocoding(address: "Infinite Loop, Cupertino, CA 95014")
}
func forwardGeocoding(address: String) {
CLGeocoder().geocodeAddressString(address, completionHandler: { (placemarks, error) in
if error != nil {
print(error ?? "Error in plscement conversion")
return
}
if (placemarks?.count)! > 0 {
let placemark = placemarks?[0]
let location = self.destinationPlacemark.location
let coordinate = location?.coordinate
print("Latitude: \(coordinate!.latitude), Longitude: \(coordinate!.longitude)")
self.destinationPlacemark = placemark!
}
})
}
}
*Updated with cause *
You had quite a few things here, so I will try to step through the changes I made to fix it:
First, why it crashes:
You create your destinationPlacemark with the following command:
So when this runs:
It is running against an empty placemark that contains no location data. By pulling the location from the retrieved placemark created in the guard statement, this issue is avoided.
Next, the working code:
Which produces:
destinationPlacemark
properly, see the above for a proper setup