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

iOS 9 Swift Programming Cookbook (2015)

Chapter 4. Contacts

4.4 Deleting Contacts

Problem

You want to delete a contact on a device.

Solution

Follow these steps:

1. Find your contact using what you learned in Recipe 4.2.

2. Instantiate an object of type CNSaveRequest.

3. Issue the deleteContact(_:) function on the request and pass your mutable contact to it.

4. Execute your request using the executeSaveRequest(_:) method of your contact store.

Discussion

NOTE

Deleting a contact from a store is irreversible. I suggest that you test your code on the simulator first and as much as possible, ask the user first whether they allow a contact to be deleted.

Let’s have a look at an example. We want to find all contacts named John and then delete the first one that we find. I am not showing an alert asking the user weather this is okay or not, because that’s not the focus of this recipe. I suggest that you do so, though.

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

}

let req = CNSaveRequest()

let mutableContact = contact.mutableCopy() as! CNMutableContact

req.deleteContact(mutableContact)

do{

try store.executeSaveRequest(req)

print("Successfully deleted the user")

} catch let e{

print("Error = \(e)")

}

} catch let err{

print(err)

}

}

See Also