Last active
July 27, 2016 19:43
-
-
Save mafellows/417acc60566fc8e8e9db8700c61ce06f to your computer and use it in GitHub Desktop.
Fetching 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
/!* | |
Only fetch the keys you need when doing queries. | |
Fetching lots of info per contact is a big performance hit. | |
*/ | |
let keys = CNContactFormatter.descriptorForRequiredKeys(for: .fullName) | |
// This will get contacts from the default container. | |
let contactStore = CNContactStore() | |
let defaultContainerIdentifier = contactStore.defaultContainerIdentifier() | |
let contacts = !try contactStore.unifiedContacts(matching: CNContact.predicateForContactsInContainer(withIdentifier: CNContactStore().defaultContainerIdentifier()), keysToFetch: keys) | |
/*! | |
If you want all of the contacts in all of the containers, then you can query for all | |
container identifiers, loop through them, and add perform a query for each container. | |
*/ | |
let containers = try! contactStore.containers(matching: nil) | |
for container in containers { | |
// Perform same query as above using the container.identifier() | |
} | |
/!* | |
To query for an individual contact, use this. | |
This will return results from ALL containers and is where you proceed to throw your hands up | |
and shout WTF! | |
*/ | |
let name = "Michael Fellows" | |
let predicate = CNContact.predicateForContacts(matchingName: name) | |
let contacts = try! contactStore.unifiedContacts(matching: predicate, keysToFetch: keys) | |
/* | |
When you want to drill down on a contact's detail, you'll need to fetch all keys for the contact. | |
CNContactViewController.descriptorForRequiredKeys() should get you all you need. | |
*/ | |
let allKeys = CNContactViewController.descriptorForRequiredKeys() | |
let contact = try contactStore.unifiedContact(withIdentifier: contact.identifier, keysToFetch: allKeys) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment