Rinat Rinat - 4 months ago 16
iOS Question

iOS can't get person's image

I have two tableViewControllers. The first one has a list of contacts. The another one shows detailed person's information.

A chunk of code of first tableViewController

ABAddressBookRef addressBook = ABAddressBookCreate();
ABRecordRef source = ABAddressBookCopyDefaultSource(addressBook);
NSArray *allPeople = (__bridge_transfer NSArray*)ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(addressBook, source,kABPersonSortByFirstName);
for ( int i = 0; i < [allPeople count]; i++ )
{
...
contactClass = [[ContactClass alloc] initWithName:name surName:surName manID:[allPeople objectAtIndex:i]];
...
}


A chunck of code of second tableViewController

ABRecordRef person = (__bridge ABRecordRef)contactClass.manID;
BOOL isHasImage = ABPersonHasImageData(person);


Variable isHasImage is always false, even if contact has an avatar. I even checked this on the first tableViewController and if person has an avatar, then it returns true and image.

Does anyone knows why I can't get contacts image?

p.s.
contactClass.manID
is type of
id
. It has a correct adress, because
ABMultiValueRef multiValue = ABRecordCopyValue((__bridge ABRecordRef)contactClass.manID, kABPersonPhoneProperty);
returns correct value in the second tableViewController

Answer

I may be too late for a solution for you, but maybe this will help others that are stuck with the same problem. Looks like ABPersonHasImageData() and ABPersonCopyImageDataWithFormat() don't work as expected on ABRecordRef copies (e.g. an ABContactRef from an array obtained using ABAddressBookCopyArrayOfAllPeople()), at leas on iOS 5.x. You may workaround it like this:

- (UIImage*)imageForContact: (ABRecordRef)contactRef {
    UIImage *img = nil;

    // can't get image from a ABRecordRef copy
    ABRecordID contactID = ABRecordGetRecordID(contactRef);
    ABAddressBookRef addressBook = ABAddressBookCreate();

    ABRecordRef origContactRef = ABAddressBookGetPersonWithRecordID(addressBook, contactID);

    if (ABPersonHasImageData(origContactRef)) {
        NSData *imgData = (NSData*)ABPersonCopyImageDataWithFormat(origContactRef, kABPersonImageFormatOriginalSize);
        img = [UIImage imageWithData: imgData]; 

        [imgData release];
    }

    CFRelease(addressBook);

    return img;
}