How to search the iphone address book for a specific phone number?

Adam Adamou picture Adam Adamou · Nov 24, 2010 · Viewed 13.1k times · Source

I am developing an app that connects to another iphone using bonjour. One of its features is when I connect to the other device it will automatically check if I have the other persons phone number. So my problem is how do I check my address book for the phone number provided by the other device?

Answer

John Carter picture John Carter · Nov 25, 2010

Here's an example extracted from one of my address book methods. I wasn't searching by phone number but this gives you an idea have how to move forward with what you need:

- (void) scanAddressBookSample
    {
    NSUInteger i;
    NSUInteger k;

    ABAddressBookRef addressBook = ABAddressBookCreate();
    NSArray *people = (NSArray *) ABAddressBookCopyArrayOfAllPeople(addressBook);

    if ( people==nil )
        {
        NSLog(@"NO ADDRESS BOOK ENTRIES TO SCAN");
        CFRelease(addressBook);
        return;
        }

    for ( i=0; i<[people count]; i++ )
        {
        ABRecordRef person = (ABRecordRef)[people objectAtIndex:i];

        //
        // Phone Numbers
        //
        ABMutableMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
        CFIndex phoneNumberCount = ABMultiValueGetCount( phoneNumbers );

        for ( k=0; k<phoneNumberCount; k++ )
            {
            CFStringRef phoneNumberLabel = ABMultiValueCopyLabelAtIndex( phoneNumbers, k );
            CFStringRef phoneNumberValue = ABMultiValueCopyValueAtIndex( phoneNumbers, k );
            CFStringRef phoneNumberLocalizedLabel = ABAddressBookCopyLocalizedLabel( phoneNumberLabel );    // converts "_$!<Work>!$_" to "work" and "_$!<Mobile>!$_" to "mobile"

            // Find the ones you want here
            //
            NSLog(@"-----PHONE ENTRY -> %@ : %@", phoneNumberLocalizedLabel, phoneNumberValue );

            CFRelease(phoneNumberLocalizedLabel);
            CFRelease(phoneNumberLabel);
            CFRelease(phoneNumberValue);
            }
        }

    [people release];
    CFRelease(addressBook);
    }