问题
In iOS it is possible to create custom labels for phone numbers and email addresses. Is there a way to remove those created labels programatically (either with CNContacts or ABAddressBook)? In other words: I don't want to delete the custom label from a contact, I want to delete the "custom label" from the system so it doesn't show up at all when someone brings up the available available list.
Attached iOS 9 source code that creates a contact in the phone book with custom labels on the email field.
func createContact() {
let contactStore = CNContactStore()
let newContact = CNMutableContact()
newContact.givenName = "Chris"
newContact.familyName = "Last"
let homeEmail = CNLabeledValue(label: "RandomLabel", value: "IGotAnEmail@Address.com")
newContact.emailAddresses = [homeEmail]
do {
let saveRequest = CNSaveRequest()
saveRequest.addContact(newContact, toContainerWithIdentifier: nil)
try contactStore.executeSaveRequest(saveRequest)
}
catch {
NSLog("Save failed")
}
}
回答1:
Contact Framework + deleteContact
This might help you.
Using this function
EDIT: I'm in a good day:
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)
}
}
EDIT: It seems you can but you need to do batch function like this:
- fetch contacts using AddressBook/ABAddressBookCopyArrayOfAllPeople
- For...in into contacts
- get the ABRecordCopyValue to get the ABMultiValueRef you want
- kABPersonEmailProperty
- kABPersonAddressProperty
- kABPersonPhoneProperty
- For...in into them
- Get the current with ABMultiValueCopyLabelAtIndex
- Compare it to the default labels (note here to get the default one)
- if no match, delete it
Hope it helps you
EDIT 2: Meh, ABAddressBook is deprecated, you need to do the same with New contact framework ... Have fun !!
来源:https://stackoverflow.com/questions/32949384/programmatically-delete-custom-phone-labels