The AB framework can be a real pain at times. But it breaks down to a series of pretty simple operations. First, you have to create an ABAddressBook instance:
ABAddressBookRef addressbook = ABAddressBookCreate();
Then you'll want to make a copy of the array of all people in the address book, and step through them looking for the data you want:
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressbook);
CFIndex numPeople = ABAddressBookGetPersonCount(addressbook);
for (int i=0; i < numPeople; i++) {
Inside your loop, you'll probably want to get a reference to the individual person:
ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);
Then you want to compare the number you have (lets call that inNumber
) to every phone number associated with that particular person. To do that, you first need a list of all the person's phone numbers:
ABMutableMultiValueRef phonelist = ABRecordCopyValue(person, kABPersonPhoneProperty);
Then, of course, you'll need to have an inner loop that loops over each of the individual person's phone numbers:
CFIndex numPhones = ABMultiValueGetCount(phones);
for (int j=0; j < numPhones; j++) {
Since the phone numbers have both numbers and labels associated with them, you'll need to extract the actual phone number string as an NSString:
CFTypeRef ABphone = ABMultiValueCopyValueAtIndex(phoneList, j);
NSString *personPhone = (NSString *)ABphone;
CFRelease(ABphone);
Now you can finally compare numbers! Do so with the standard NSString comparison methods, but remember that you need to worry about formatting, etc.
Once you find the person who has a phone number matching inNumber
, you'll want the extract that person's image into a UIImage
:
CFDataRef imageData = ABPersonCopyImageData(person);
UIImage *image = [UIImage imageWithData:(NSData *)imageData];
CFRelease(imageData);
When it comes time to exit, you'll need to clean up memory. A general rule of thumb for the AB framework is that anything with Get
in the function name you don't need to release, and anything with Copy
or Create
, you do need to release. So, in this case you'll need to CFRelease()
phonelist
, allPeople
, and addressbook
, but not numPeople
, person
, or numPhones
.