I copied a Swift-func last week out of the internet Link. The function should convert 2 CLLocationDegrees (latitude and longitude) into an address. From the address I only need the postal code. The postal code gets saved in var plz: String
. Then if everything works out my function should return plz. Somehow it doesn't and compiles the function code weirdly.
Even with getter and setter methods or local variables, I couldn't get my postal code to be returned at the right time. Is it possible to force a wait or something?
Code:
import Foundation
import CoreLocation
class GeoCodeLocation{
func reverseGeocoding(latitude: CLLocationDegrees, longitude: CLLocationDegrees) -> String{
var plz:String?
let geocoder = CLGeocoder()
let location = CLLocation(latitude: latitude, longitude: longitude)
geocoder.reverseGeocodeLocation(location, completionHandler: {(placemarks, error) -> Void in
if error != nil {
print("Failed to retrieve address")
return
}
if let placemarks = placemarks, let placemark = placemarks.first {
print("DEBUG: placemark.plz! ->\(placemark.plz!)")
plz = placemark.plz!
print("DEBUG: plz after initialising \(String(describing: plz))")
}
else
{
print("No Matching Address Found")
}
})
print("DEBUG: Postalcode before return \(String(describing: plz))")
if let plz = plz{
return plz
}
return ""
}
}
This is the order of the print statements:
DEBUG: Postalcode before return nil
DEBUG: placemark.plz! ->1220
DEBUG: plz after initialising Optional("1220")
How do I return the postal code at the right time?