Update phone contact single item in array

215 views Asked by At

I'm trying to update 1 single item in the iphone contacts. I'm updating the email array and don't want to affect the others in the array.

For instance, I'm changing the "home" email address from my app, but if they also have a "work" email in their phone contacts it deletes it and only puts in the new one. I need to keep all others fields in the array. Same for phone or address.

This is my update:

let homeEmailEntry : String = email!
let homeEmail = CNLabeledValue(label:CNLabelHome, value:homeEmailEntry as NSString)
contactToUpdate.emailAddresses = [homeEmail]

let saveRequest = CNSaveRequest()
saveRequest.update(contactToUpdate)
try store.execute(saveRequest)

That adds the home email but wipes out the work email or anything else in the array.

1

There are 1 answers

1
Callam On BEST ANSWER

You need to concatenate the existing email addresses with the new one(s) you're adding.

contact.emailAddresses = contactToUpdate.emailAddresses + [homeEmail]

Or alternatively, you could append it.

contact.emailAddresses.append(homeEmail)

I am unsure what happens here if there's already a home email address, but you can remove the existing home email address before appending a new one.

contact.emailAddresses = contact.emailAddresses.filter({ $0.label != CNLabelHome }) + [homeEmail]