Reputation:
In Swift 3, I use the new Contact Framework to manipulate contacts, but I don't have any solution for fetching duplicate contacts.
Any idea how to achieve this?
Upvotes: 3
Views: 1918
Reputation: 437552
I'd build a dictionary keyed by name, and then filter down to just those with more than one occurrence of the name:
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 }
Upvotes: 2
Reputation: 3096
You can do something like this:
/// 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)
}
Upvotes: 2