Swift 3 - Set Home Address for a New CNContact Instance

Published Apr 18, 2017
Swift 3 - Set Home Address for a New CNContact Instance

Here's how you would create a home address for a new contact in Swift 3.x:

let store = CNContactStore()
let contact = CNMutableContact()
contact.familyName = "Tester"
contact.givenName = "Bad"
// Address
let address = CNMutablePostalAddress()
address.street = "Your Street"
address.city = "Your City"
address.state = "Your State"
address.postalCode = "Your ZIP/Postal Code"
address.country = "Your Country"
let home = CNLabeledValue<CNPostalAddress>(label:CNLabelHome, value:address)
contact.postalAddresses = [home]
// Save
let saveRequest = CNSaveRequest()
saveRequest.add(contact, toContainerWithIdentifier: nil)
try? store.execute(saveRequest)

If you wanted to create a work address, then you'd create another CNMutablePostalAddress instance to hold the work address information, then create another CNLabeledValue<CNPostalAddress> with a label of CNLabelWork and add the new CNLabeledValue<CNPostalAddress> instance to the final postalAddresses array as well.

Discover and read more posts from Fahim Farook
get started
Enjoy this post?

Leave a like and comment for Fahim

Sohail Basha
2 months ago

Hi Fahim,
Great guide by the way. I was wondering if you could go over how to properly create your own custom CNLabeledValue<>'s. When I try making mine with programmatically created contact, my CNLabels are saved as the default labels and it’s got me lost.

Get curated posts in your inbox

Read more posts to become a better developer