10

In the latest Contacts framework for iOS9, how to retrieve only CNContact that has a valid email address?

Current code:

func getContacts() -> [CNContact] {
    let contactStore = CNContactStore()
    let predicate: NSPredicate = NSPredicate(format: "")
    let keysToFetch = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactEmailAddressesKey]

    do {
        return try contactStore.unifiedContactsMatchingPredicate(predicate, keysToFetch: keysToFetch)
    } catch {
        return []
    }
}
Eugene Teh
  • 263
  • 2
  • 3
  • 12

1 Answers1

19

For now (iOS 9.0) it seems that no predicates (see CNContact Predicates) are available to filter contacts by email address!

You can't write a custom predicate to filter contacts, as the doc says: "Note that generic and compound predicates are not supported by the Contacts framework"

But of course you can do it "manually", I show you an example using fast enumeration:

let contactStore = CNContactStore()
fetchRequest.unifyResults = true //True should be the default option
do {
    try contactStore.enumerateContactsWithFetchRequest(CNContactFetchRequest(keysToFetch: [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactEmailAddressesKey])) {
        (contact, cursor) -> Void in
        if (!contact.emailAddresses.isEmpty){
            //Add to your array
        }
    }
}
catch{
    print("Handle the error please")
}

Note:

In newer versions of Swift, the call to contactStore.enumerateContactsWithFetchRequest needs to be updated to:

try contactStore.enumerateContacts(with: CNContactFetchRequest(keysToFetch: [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactEmailAddressesKey] as [CNKeyDescriptor])) {
rmaddy
  • 314,917
  • 42
  • 532
  • 579
andreacipriani
  • 2,519
  • 26
  • 23
  • How would you use this with a CNContactPickerViewController? Is it possible? Or would you have to create a new View controller to select your contacts? – Frederic Adda Nov 18 '15 at 08:11
  • You can look at the method: predicateForEnablingContact of CNContactPickerViewController – andreacipriani Nov 19 '15 at 11:50
  • @adreacipriani, `fetchRequest:CNContactFetchRequest` have predicate variable and we can find particular contact for a predicate, right? Can you show an example? – Dima Deplov Nov 15 '16 at 16:35