Tarvo Mäesepp Tarvo Mäesepp - 6 months ago 122
iOS Question

Programmatically remove contact from adress book on specific time in swift

I am trying to programmatically remove contacts from address book on specific time. Is it even possible in Swift and do Apple allow it?. I'm already familiar with

CNContactStore
because I have got working adding contacts into phonebook. Granted access into Contacts etc.. But I do not know how to programmatically delete contacts from addressbook(forever) on specific time.

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)
}