iphoneswift3cllocationmanagercncontactcncontactstore

Programmatically save a home address to a new contact using CNContactStore? Swift 3


I would like to programmatically create a contact in my app and save it into actual contacts using apples Contacts framework. I can create one with a first name, last name, and even work with dates.

I start with

let contact = CNMutableContact()

and end with

let store = CNContactStore()
let saveRequest = CNSaveRequest()
saveRequest.add(contact, toContainerWithIdentifier: nil)
try? store.execute(saveRequest)

but I can't figure out how to do it with a home address. Any help would be appreciated, thanks. Would love to do it via location coordinates or even a string of a city, state, street, etc.

Thank you.


Solution

  • Here's how you would create a home address:

    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.