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

こ雲淡風輕ζ 提交于 2019-12-22 08:52:36

问题


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!


回答1:


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


来源:https://stackoverflow.com/questions/37225374/programmatically-remove-contact-from-adress-book-on-specific-time-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!