Tarvo Mäesepp Tarvo Mäesepp - 6 months ago 63
Swift Question

Programmatically remove contact from adressbook in swift

I am trying to programmatically remove contacts from addressbook. Is it even possible in Swift? Actually I want to use

NSTimer
for this but it is just one idea. First I would like to just try to delete contact from Adressbook by button click or something like that. I'm already familiar with
CNContactStore
because I have got working adding contacts into phonebook. Granted access into Contacts etc..

Any help is appreciated!

Answer

REFERENCE:

http://www.ios-blog.co.uk/tutorials/swift/contacts-framework-p2/


EXPLANATION (FROM THE LINK):

Delete Contact

"The iOS contacts framework gives us the function deleteContact(:) to help us delete contacts. Hopefully you’ve understood this tutorial enough so far to proceed as I’m only going to outline the process and let you have a try. Just like we have throughout this tutorial we are going to instantiate an object of type CNSaveRequest, Issue the deleteContact(:) function that I just mentioned and pass the mutable contact to it. Then, Like when we created contacts or updated contacts we are going to use the executeSaveRequest(_:).

Please note that Delete means Delete! Contacts that are deleted can not be obtained again. This shouldn’t matter too much on the simulator but you do need to make sure that you have safety protocols in place so that you don’t delete a users contacts.

So, Did you manage to get the delete working? Ok, Fine, I will post the full code so you can see."


SOLUTION (FROM THE LINK):

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
  }

  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("Success, You deleted the user")
  } catch let e{
    print("Error = \(e)")
  }
} catch let err{
   print(err)
}