San Lewy
San Lewy

Reputation: 136

Update existing 'Contacts' Phone number?

I have code to fetch and display User data from Contacts (various Name properties plus the array of Phone numbers). By making a CNMutableContact, I can update any of the Name properties. But I can only display Phone numbers (from CNLabeledValue via ".digits"). Is it possible to also update Phone numbers? I can't change "digits" in the CNMutableContact because it is 'read-only'. I have seen and understand cautions on accessing CNLabeledValue "digits", but would still like to proceed.

Suggestions?

Upvotes: 1

Views: 1320

Answers (1)

ggoncalves
ggoncalves

Reputation: 41

Maybe is a little late to answer this question. However, on the given exemple, you can only add phone numbers. So, to update phone you would, at best, replace removing phone numbers and add new ones.

Replacing a phonenumber entry in this approach would result in changing the phonenumber's identifier.

This should be not the behaviour you are expecting, since you are changing a phone number of an existing entry. And we want to keep the phone identifier intact.

You should use settingValue from CNLabeledValue see: Apple Documentation

// Clone to a mutable contact
let mutableContact = contact.mutableCopy() as! CNMutableContact

// Here's the catch
let updatedPhone = mutableContact.phoneNumbers[0].settingValue(CNPhoneNumber(stringValue: "newPhone"))

// Be aware that in this example, I only have on phone number. For multiple phones, would need to handle multiple phones properly in the array.
mutableContact.phoneNumbers = [updatedPhone]

Upvotes: 3

Related Questions