1

In my iOS app, I want to find the phone number of the contact that matches the name.

CFErrorRef *error = NULL;

// Create a address book instance.
ABAddressBookRef addressbook = ABAddressBookCreateWithOptions(NULL, error);

// Get all people's info of the local contacts.
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressbook);
CFIndex numPeople = ABAddressBookGetPersonCount(addressbook);
for (int i=0; i < numPeople; i++) {

    // Get the person of the ith contact.
    ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);
    ## how do i compare the name with each person object?
}
woz
  • 10,888
  • 3
  • 34
  • 64
mopodafordeya
  • 635
  • 1
  • 9
  • 26

1 Answers1

0

You can get the person's name with ABRecordCopyCompositeName, and test if the search string is contained in the name with CFStringFind.

For example, to find contacts with "Appleseed" in his name:

CFStringRef contactToFind = CFSTR("Appleseed");

CFErrorRef *error = NULL;

// Create a address book instance.
ABAddressBookRef addressbook = ABAddressBookCreateWithOptions(NULL, error);

// Get all people's info of the local contacts.
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressbook);
CFIndex numPeople = ABAddressBookGetPersonCount(addressbook);
for (int i=0; i < numPeople; i++) {

    // Get the person of the ith contact.
    ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);

    // Get the composite name of the person
    CFStringRef name = ABRecordCopyCompositeName(person);

    // Test if the name contains the contactToFind string
    CFRange range = CFStringFind(name, contactToFind, kCFCompareCaseInsensitive);

    if (range.location != kCFNotFound)
    {
        // Bingo! You found the contact
        CFStringRef message = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("Found: %@"), name);
        CFShow(message);
        CFRelease(message);
    }

    CFRelease(name);
}

CFRelease(allPeople);
CFRelease(addressbook);

Hope this helps. Although your question was asked 5 months ago...

howanghk
  • 3,070
  • 2
  • 21
  • 34