4

I am trying to build iPhone App with digits Find a friend feature

I can get list of matching digitUserID from Digits.

Now I am struggling to match UserID and CNContacts.

Please point any examples to deal this.

As update:

do 
{
    try contactStore.enumerateContactsWithFetchRequest(CNContactFetchRequest(keysToFetch: [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactMiddleNameKey, CNContactEmailAddressesKey,CNContactPhoneNumbersKey])) {
        (contact, cursor) -> Void in

        self.results.append(contact)
    }
}
catch{
    print("Handle the error please")
}

The above I have managed to get all contact but I don't know how to pass a phone number filter into this and get exact contact match with CNContact

Rob
  • 415,655
  • 72
  • 787
  • 1,044
Kaviyarasu Arasu
  • 329
  • 5
  • 13

1 Answers1

11

Ideally, one would have expected predicate of the CNContactFetchRequest to do the job, but that (still; argh) only accepts a narrow list of predicates defined with CNContact (e.g. CNContact predicateForContacts(matchingName:) or predicateForContacts(withIdentifiers:). It doesn't even accept the block-based NSPredicate.

So, you have to enumerate through, looking for matches yourself, e.g.

let request = CNContactFetchRequest(keysToFetch: [
    CNContactGivenNameKey as CNKeyDescriptor,
    CNContactFamilyNameKey as CNKeyDescriptor,
    CNContactMiddleNameKey as CNKeyDescriptor,
    CNContactEmailAddressesKey as CNKeyDescriptor,
    CNContactPhoneNumbersKey as CNKeyDescriptor
])

do {
    try contactStore.enumerateContacts(with: request) { contact, stop in
        for phone in contact.phoneNumbers {
            // look at `phone.value.stringValue`, e.g.

            let phoneNumberDigits = String(phone.value.stringValue.characters.filter { String($0).rangeOfCharacter(from: CharacterSet.decimalDigits) != nil })

            if phoneNumberDigits == "8885551212" {
                self.results.append(contact)
                return
            }
        }
    }
} catch let enumerateError {
    print(enumerateError.localizedDescription)
}

Regarding matching "digit UserID", I don't know what that identifier is (is it a Contacts framework identifier or Digits' own identifier?).

Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • oh that's my own identifier. – Kaviyarasu Arasu Aug 18 '16 at 04:37
  • Would it be possible to modify the answer to include a search string (name, telephone, email)? If not, could you point me to another solution. Thanks – ICL1901 Aug 06 '17 at 09:59
  • @DavidDelMonte - Sure. If it were a simple search, you could supply a [`predicate`](https://developer.apple.com/documentation/contacts/cncontactfetchrequest/1403080-predicate). But I don't think that will search inside phone numbers, so you may have to add an `if` statement inside your `for` loop, checking for your searched string in whatever fields you want. See https://stackoverflow.com/a/42749708/1271826. – Rob Aug 06 '17 at 15:41