点击“确定”提醒按钮后如何从表格视图中删除重复的联系人?
这是我的findDuplicateContacts()
@objc fileprivate func findDuplicateContacts() {
let keys = [CNContactIdentifierKey as CNKeyDescriptor, CNContactFormatter.descriptorForRequiredKeys(for: .fullName)]
let request = CNContactFetchRequest(keysToFetch: keys)
var contactsByName = [String: [CNContact]]()
do {
try self.contactStore.enumerateContacts(with: request) { contact, stop in
guard let name = CNContactFormatter.string(from: contact, style: .fullName) else { return }
contactsByName[name] = (contactsByName[name] ?? []) + [contact] // or in Swift 4, `contactsByName[name, default: []].append(contact)`
}
} catch let err {
print("error:", err)
}
let duplicates = contactsByName.filter { $1.count > 1 }
let alert = UIAlertController(title: "Alert", message: "Number of duplicates: \(duplicates.count)", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: {(action:UIAlertAction!) in
//HERE I WANT TO REMOVE DUPLICATES
print("you have pressed the ok button")
}))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
print(duplicates)
self.tableView.reloadData()
}
提前致谢
答案 0 :(得分:1)
您应该使用CNSaveRequest
类func delete(_ contact: CNMutableContact)
方法,使用func execute(_ saveRequest: CNSaveRequest)
类的CNContactStore
方法执行
此示例删除所有其他联系人并仅保留一个(位置0),但您可以添加一种方法来确定哪个联系人更完整并保留该联系人
完整代码
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: {(action:UIAlertAction!) in
print("you have pressed the ok button")
var arrayOfContactsRequests : [CNSaveRequest] = []
for dict in duplicates {
for (index,contact) in dict.value.enumerated() {
if(index != 0) {
let saveRequest = CNSaveRequest()
saveRequest.delete(contact.mutableCopy() as! CNMutableContact)
arrayOfContactsRequests.append(saveRequest)
}
}
}
debugPrint(duplicates)
for request in arrayOfContactsRequests {
do{
try self.contactStore.execute(request)
}
catch let err {
print("error:", err)
}
}
}))
的帮助下,这个答案是可能的