In an app, I am displaying the details of the contacts using ABRecordRef. I am using the keys kABPersonAddressCityKey, kABPersonAddressStateKey, kABPersonAddressZIPKey, kABPersonAddressCountryKey. Everything works fine. But I don't know in which format to display the addresses. What I mean is, if you see the Contacts app, the addresses are displayed in a particular format for different countries. Some examples,
US
Street
City State ZIP
Country
India
Street
Province
City PIN
Country
Australia
Street
Suburb State ZIP
Country
Now I don't know how to find the format for different countries.
1.Is there any way to find the address format based on country/country codes?
2.Is there a way we can get the fully formatted address using a single function, like we use ABRecordCopyCompositeName() to get the full name?
From iOS 9.0 / macOS 10.11 / watchOS 2.0 on you should use CNPostalAddressFormatter instead:
The CNPostalAddressFormatter class formats the postal address in a contact. This class handles international formatting of postal addresses.
Below code is in Swift 3 but it is trivial to convert it to Objc
let postalAddress = CNMutablePostalAddress()
postalAddress.street = street
postalAddress.postalCode = zipCode
postalAddress.city = city
postalAddress.state = state
postalAddress.country = country
postalAddress.isoCountryCode = countryCode
let formattedAddress = CNPostalAddressFormatter.string(from: postalAddress, style: .mailingAddress)
Make sure you set the ISO country code property, this is used to determine the format of the address.
Example:
postalAddress.street = "Main Street 1"
postalAddress.postalCode = "67067"
postalAddress.city = "Ludwigshafen"
postalAddress.state = "Rhineland-Palatinate"
postalAddress.country = "Germany"
postalAddress.isoCountryCode = "DE"
leads to this
Main Street 1
67067 Ludwigshafen
Germany
whereas
postalAddress.isoCountryCode = "US"
leads to
Main Street 1
Ludwigshafen Rhineland-Palatinate 67067
Germany
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With