Skip to content

Instantly share code, notes, and snippets.

@brcosm
Created September 11, 2011 19:08
Show Gist options
  • Save brcosm/1209979 to your computer and use it in GitHub Desktop.
Save brcosm/1209979 to your computer and use it in GitHub Desktop.
Objective-C Image for Contact in Address Book
@implementation Contacts
+ (UIImage *)imageForContactWithName:(NSString *)name {
// Create a CF string reference from the NSString pointer
CFStringRef cfName = objc_unretainedPointer(name);
UIImage *personImage = nil;
// Create a reference to the address book
ABAddressBookRef addressBook = ABAddressBookCreate();
// Create a reference to an array of all the people that match the passed name string
CFArrayRef people = ABAddressBookCopyPeopleWithName(addressBook, cfName);
int num = CFArrayGetCount(people);
// Create a reference to the first match if there was a match
ABRecordRef person = (num > 0) ? CFArrayGetValueAtIndex(people, 0) : NULL;
// If there was a matching contact and that contact had image data
if (num > 0 && ABPersonHasImageData(person)) {
// Have to use objc_unretainedObject for toll-free bridging in Xcode 4.3 w/ ARC
CFDataRef imageData = ABPersonCopyImageData(person);
NSData *personImageData = [NSData dataWithData:(NSData *)objc_unretainedObject(imageData)];
CFRelease(imageData);
personImage = [UIImage imageWithData:personImageData];
} else if (num > 0) {
// Contact existed but there was no image data
personImage = [UIImage imageNamed:@"smile.png"];
} else {
// Contact did not exist
personImage = [UIImage imageNamed:@"frown.png"];
}
CFRelease(addressBook);
CFRelease(people);
return personImage;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment