EmptyStack
EmptyStack

Reputation: 51374

Contact address format for different countries

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?

Upvotes: 4

Views: 4379

Answers (2)

HAS
HAS

Reputation: 19863

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

Upvotes: 10

shannoga
shannoga

Reputation: 19869

Try this link ABCreateStringWithAddressDictionary

It looks like you need to use: ABCreateStringWithAddressDictionary that will return:

Returns a formatted address from an address property. (From Apple)

Good luck

Upvotes: 5

Related Questions