在Contacts Framework中查找重复的联系人

时间:2017-09-01 17:01:58

标签: ios swift3 contacts

在Swift 3中,我使用新的联系框架来操纵联系人,但我没有任何解决方案来获取重复的联系人。

知道如何实现这个目标吗?

2 个答案:

答案 0 :(得分:2)

您可以这样做:

/// Find Duplicates Contacts In Given Contacts Array
func findDuplicateContacts(Contacts contacts : [CNContact], completionHandler : @escaping (_ result : [Array<CNContact>]) -> ()){
    let arrfullNames : [String?] = contacts.map{CNContactFormatter.string(from: $0, style: .fullName)}
    var contactGroupedByDuplicated : [Array<CNContact>] = [Array<CNContact>]()
    if let fullNames : [String] = arrfullNames as? [String]{
        let uniqueArray = Array(Set(fullNames))
        var contactGroupedByUnique = [Array<CNContact>]()
        for fullName in uniqueArray {
            let group = contacts.filter {
                CNContactFormatter.string(from: $0, style: .fullName) == fullName
            }
            contactGroupedByUnique.append(group)
        }
        for items in contactGroupedByUnique{
            if items.count > 1 {
                contactGroupedByDuplicated.append(items)
            }
        }
    }
    completionHandler(contactGroupedByDuplicated)
}

答案 1 :(得分:1)

我会建立一个按名称键入的字典,然后过滤到只有多个名称出现的字典:

let keys = [CNContactIdentifierKey as CNKeyDescriptor, CNContactFormatter.descriptorForRequiredKeys(for: .fullName)]
let request = CNContactFetchRequest(keysToFetch: keys)
var contactsByName = [String: [CNContact]]()
try! self.store.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)`
}
let duplicates = contactsByName.filter { $1.count > 1 }