I am trying to generate a Formatted Full address using CLGeocoder in Swift 3. I referred to this SO thread to get the code given below.
However, sometimes the app crashe
Formatting addresses is hard because each country has its own format.
With a few lines of code, you can get the correct address format for each country and let Apple handle the differences.
Since iOS 11, you can get a Contacts framework address:
extension CLPlacemark {
@available(iOS 11.0, *)
open var postalAddress: CNPostalAddress? { get }
}
This extension is part of the Contacts
framework.
This means, this feature is invisible to you in the XCode
code completion until you do
import Contacts
With this additional import, you can do something like
CLGeocoder().reverseGeocodeLocation(location, preferredLocale: nil) { (clPlacemark: [CLPlacemark]?, error: Error?) in
guard let place = clPlacemark?.first else {
print("No placemark from Apple: \(String(describing: error))")
return
}
let postalAddressFormatter = CNPostalAddressFormatter()
postalAddressFormatter.style = .mailingAddress
var addressString: String?
if let postalAddress = place.postalAddress {
addressString = postalAddressFormatter.string(from: postalAddress)
}
}
and get the address formatted in the format for the country in the address.
The formatter even supports formatting as an attributedString.
Prior to iOS 11, you can convert CLPlacemark
to CNPostalAddress
yourself and still can use the country specific formatting of CNPostalAddressFormatter
.