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.

1 Answers1

8

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.

Fahim
  • 3,466
  • 1
  • 12
  • 18
  • Thank you! I'll definitely try this out. Also, without reverse geocoding, do you think it would be possible to do it with a location? –  Mar 30 '17 at 00:12
  • What you need to look into is the `CNPostalAddress` class. As far as I can tell, it only takes actual address values. There is no obvious way to pass it a location that I can see but you might want to do a little deeper digging ... just in case :) – Fahim Mar 30 '17 at 00:48
  • I reverse geocoded my location to where my CLLocation gives me strings for a city, state, and street. After that I followed your code and a location comes up blank when checking my Contacts app :/ –  Mar 30 '17 at 01:51
  • Does the address information you added via reverse geocoding appear in Contacts? – Fahim Mar 30 '17 at 01:53
  • Then you should first verify that reverse geocoding actually returns values. Does it? And if it does, check that the save request for the contact actually works. You can verify this by catching any errors thrown when executing the save request. My feeling is that you'll find that there is an issue with one of those steps. – Fahim Mar 30 '17 at 02:05
  • I got it finally. Store was being called before the address was given a street, city, etc. –  Apr 12 '17 at 16:25
  • Great :) I'm glad you were able to figure it out! – Fahim Apr 12 '17 at 23:49