How to fetch contact image from ABAddressBook API asynchrously?

114 views Asked by At

I'm reading contact's image from c ABAddressBook API like this:

NSData *photoData;
ABRecordRef personRef = ABAddressBookGetPersonWithRecordID(bookRef, ID);

// Photo data
if (ABPersonHasImageData(personRef)) {
    photoData = (__bridge_transfer NSData *) ABPersonCopyImageData(personRef);
}

The problem is that this need's to be done asynchrously, because there are displaying issues in tableView while listing all contacts. I know there is one function in API called 'beginLoadingImageDataForClient' but I am not able to find out how to use it. Could you help me to implement it this way? Thanks

1

There are 1 answers

1
Ryan Dignard On

Try this

@property (nonatomic, strong) NSData* photoData;    
...

__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    __strong typeof(self) strongSelf = weakSelf;
    strongSelf.photoData = (__bridge_transfer NSData *) ABPersonCopyImageData(personRef);
    dispatch_async(dispatch_get_main_queue(), ^{
        __strong typeof(self) strongSelf = weakSelf;
        [strongSelf.tableView reloadData];
    });
});

We're pushing the data request off the main thread, then calling back to the main thread when the data is ready.