Skip to content

Instantly share code, notes, and snippets.

@roimulia
Created May 21, 2018 00:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roimulia/588be03804d9e97c0b157730e52bf516 to your computer and use it in GitHub Desktop.
Save roimulia/588be03804d9e97c0b157730e52bf516 to your computer and use it in GitHub Desktop.
Fetch Contacts
func findContactsOnBackgroundThread ( completionHandler:@escaping (_ contacts:[CNContact]?)->()) {
DispatchQueue.global(qos: .userInitiated).async(execute: { () -> Void in
let keysToFetch = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName),CNContactPhoneNumbersKey,CNContactViewController.descriptorForRequiredKeys()] as! [CNKeyDescriptor] //CNContactIdentifierKey
let fetchRequest = CNContactFetchRequest( keysToFetch: keysToFetch)
var contacts = [CNContact]()
fetchRequest.unifyResults = true
fetchRequest.sortOrder = .none
do {
try CNContactStore().enumerateContacts(with: fetchRequest) { (contact, stop) -> Void in
//do something with contact
if contact.phoneNumbers.count > 0 {
contacts.insert(contact, at: 0)
}
}
} catch let e as NSError {
print(e.localizedDescription)
}
DispatchQueue.main.async(execute: { () -> Void in
completionHandler(contacts)
})
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment