iosswiftcontacts-framework

swift contacts framework, predicate with namePrefix rather than a name


I am trying to obtain a list of all contacts that show a particular 'namePrefix' (e.g. Mr, Mrs or Miss etc.). However, have come up against a brick wall.

I used the following code with Predicate to obtain results for a name search, which is fine...

let store = CNContactStore()
let keysToFetch = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactNamePrefixKey, CNContactPhoneNumbersKey]

    // Predicate = prob...? How get namePrefix
    let predicate = CNContact.predicateForContactsMatchingName("James")

    do {
        let fetchedContacts = try store.unifiedContactsMatchingPredicate(predicate, keysToFetch: keysToFetch)

        for result in fetchedContacts {
            print("\(result.givenName) \(result.familyName) \(result.phoneNumbers) \(result.namePrefix)")
        }
    } catch {
        print("Error unable to fetch")
    }

However, I need the "namePrefix". Apple documentation shows that namePrefix is available as a property, but with trial and error, unable to find a way to use it to filter my results with 'predicate'. I thought there may be a possibility by use of... "predicateForContactsWithIdentifiers" but unable to find an example.

I'd like to know if namePrefix filter can be done via predicate line above somehow? or if not if it can be done with "predicateForContactsWithIdentifiers"?

I understand Apple don't allow customs for predicate other than ...

predicateForContactsMatchingName // predicateForContactsInContainerWithIdentifier predicateForContactsWithIdentifiers // predicateForContactsInGroupWithIdentifier

However, I'm looking for a work around, if the direct root isn't available...?

Many thanks in advance.


Solution

  • After fetching all the contacts you can use one more predicate:

    let prefixPredicate = NSPredicate(format: "namePrefix = 'smth'")
    let searchedByPrefix = (fetchedContacts as NSArray)
    print(searchedByPrefix.filteredArrayUsingPredicate(prefixPredicate))
    

    Where 'smth' is a string value that you are looking for.

    If you are looking for a direct way using contacts framework, there is no such solution, as it looks to me.