Programmatically remove contact from adress book on specific time in swift [closed]
Asked Answered
K

1

6

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 CNContactStorebecause 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!

Klayman answered 14/5, 2016 at 10:18 Comment(1)
Actually I want to use NSTimer Why?Leporid
C
17

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)
}
Conversazione answered 14/5, 2016 at 10:37 Comment(6)
Why the downvote ? I require an explanation !Conversazione
thank you so much for your help. It works as it should. And I really do not know why the downvote. Cheers :) And actually I just found the same solution by googling too, I must be dumb :DCoppola
@TarvoMäesepp Haha :D Happy to help !Conversazione
@TarvoMäesepp Idk, I upvoted your question :/Conversazione
should declare store in the first line such as : let store = CNContactStore()Hoffarth
Ive deleted the contact using above method, but contact is not disappearing from native contacts app, still i could able to find the same contact.Why So?Assuasive

© 2022 - 2024 — McMap. All rights reserved.