6

The Apple documentation suggests using CNPostalAddressFormatter to display addresses as a formatted string, which helps immensely with internationalization.

This code:

let postalString = CNPostalAddressFormatter.string(from: postalAddress.value, style: .mailingAddress)

yields this work address for the John Appleseed contact on the simulator:

3494 Kuhl Avenue
Atlanta GA 30303

The address is missing the comma between city and state.

Is there a way for CNPostalAddressFormatter to insert the comma? The documentation doesn't list anything.

If not, doesn't this mean you must manually format addresses for each locality, and are unable to use CNPostalAddressFormatter for localization?

Crashalot
  • 33,605
  • 61
  • 269
  • 439
  • Did you ever find a solution to this? Experiencing the same issue. – Joel Bell Apr 22 '19 at 20:23
  • Good question. I'm also experiencing this. I ended up hacking it and just adding the comma to the end of the city string before getting the formatted string from the formatter, but I'll admit that's not a very good solution. – Brian Sachetta Nov 18 '19 at 22:21
  • I would suppose that a regex could be used on the results and it could apply a comma just before the space and 2-letter state abbreviation by knowing that first there's a set of numbers for the zip at the end, and then 2-letter state, and then it applies the comma before the space before the state. I'll probably end up implementing this myself if it ends up working. Thank you btw for the code that helped me get the Postal Address Formatter working as I couldn't find any example code - which Apple seems notoriously inept at providing. – Jason Cramer Dec 16 '21 at 19:57

1 Answers1

0

Here is my snippet to add "," after city for US addresses.

#if canImport(Contacts)
import Contacts

public extension CLPlacemark {

  /// Get a formatted address.
  var formattedAddress: String? {
    guard let postalAddress = postalAddress else {
      return nil
    }

    let updatedPostalAddress: CNPostalAddress
    if postalAddress.isoCountryCode == "US" {
      // add "," after city name
      let mutablePostalAddress = postalAddress.mutableCopy() as! CNMutablePostalAddress
      mutablePostalAddress.city += ","
      updatedPostalAddress = mutablePostalAddress
    } else {
      updatedPostalAddress = postalAddress
    }

    return CNPostalAddressFormatter.string(from: updatedPostalAddress, style: .mailingAddress)
  }
}
#endif
Honghao Z
  • 1,419
  • 22
  • 29