Created
May 21, 2018 00:35
-
-
Save roimulia/588be03804d9e97c0b157730e52bf516 to your computer and use it in GitHub Desktop.
Fetch Contacts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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