Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift iOS9 New Contacts Framework - How to retrieve only CNContact that has a valid email address?

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 []
    }
}
like image 810
Eugene Teh Avatar asked Sep 19 '15 07:09

Eugene Teh


People also ask

How do I get all my contacts in Swift?

Swift 4 and 5. import ContactsUI func phoneNumberWithContryCode() -> [String] { let contacts = PhoneContacts. getContacts() // here calling the getContacts methods var arrPhoneNumbers = [String]() for contact in contacts { for ContctNumVar: CNLabeledValue in contact. phoneNumbers { if let fulMobNumVar = ContctNumVar.


1 Answers

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])) {
like image 110
andreacipriani Avatar answered Nov 16 '22 00:11

andreacipriani