Updating Contacts - Contacts - iOS 9 Swift Programming Cookbook (2015)

iOS 9 Swift Programming Cookbook (2015)

Chapter 4. Contacts

4.3 Updating Contacts

Problem

You have an existing contact whose properties you want to update.

Solution

Call the mutableCopy() method of your CNContact class. This will give you an instance of the CNMutableContact. Once you have a mutable contact, you can change her properties as you would with a contact of type CNContact. Once done editing, instantiate CNSaveRequest, issue the updateContact(_:) method on it, and pass your mutable contact to that method. Now that you have the request object, pass it to the executeSaveRequest(_:) method of your store to update the contact.

Discussion

Let’s check an example. Let’s say that we want to find a contact named “John” and then add a new email address to it, if it doesn’t already have it. I am not going to explain the things that we learned in Recipe 4.2, so let’s dive in. Figure 4-3 shows the contact we will change. The contact comes pre-filled in your iOS simulator, with only one work email address. We are going to add another work email to this list.

Figure 4-3. Current state of the contact

NSOperationQueue().addOperationWithBlock{[unowned store] in

let predicate = CNContact.predicateForContactsMatchingName("john")

let toFetch = [CNContactEmailAddressesKey]

do{

let contacts = try store.unifiedContactsMatchingPredicate(predicate,

keysToFetch: toFetch)

guard contacts.count > 0 else{

print("No contacts found")

return

}

//only do this to the first contact matching our criteria

guard let contact = contacts.first else{

return

}

...

NOTE

We are only adding this new email to the first contact that matches our criteria.

Now we have a contact object that matches our criteria. Let’s see whether he already has this email address, and bail out if he does:

let newEmail = "newemail@work.com"

for email in contact.emailAddresses{

if email.value as! String == newEmail{

print("This contact already has this email")

return

}

}

Now that we are sure he didn’t have this email address already in the list, we will add it:

let john = contact.mutableCopy() as! CNMutableContact

let emailAddress = CNLabeledValue(label: CNLabelWork,

value: "newemail@work.com")

john.emailAddresses.append(emailAddress)

let req = CNSaveRequest()

req.updateContact(john)

try store.executeSaveRequest(req)

print("Successfully added an email")

Now if we look at our contact in the list, we can see the new email address added (see Figure 4-4):

Figure 4-4. The new email address is added to our contact.

See Also