iPhone AddressBook Names in App

There’s lots of sites that talk about getting the AddressBook and such, but I wanted a good example and had a hard time finding code just to get the address book names.

Address Book Programming Guide for iPhone OS: Interacting Directly with the Address Book Database

Here's one way...[sourcecode lang="cpp"]

ABAddressBookRef addressBook = ABAddressBookCreate();

NSArray *people = (NSArray*) ABAddressBookCopyArrayOfAllPeople(addressBook);
NSInteger addressesCount = [people count];

NSMutableArray *allResults = [[[NSMutableArray alloc] init] autorelease];

for (CFIndex i = 0; i < addressesCount; i++) { ABRecordRef record = [[people objectAtIndex:i] retain]; NSString *firstName = (NSString *)ABRecordCopyValue(record, kABPersonFirstNameProperty); NSString *lastName = (NSString *)ABRecordCopyValue(record, kABPersonLastNameProperty); NSString *fullName = nil; if (ABPersonGetCompositeNameFormat() == kABPersonCompositeNameFormatFirstNameFirst) fullName = [NSString stringWithFormat:@"%@ %@", firstName, lastName]; else fullName = [NSString stringWithFormat:@"%@, %@", lastName, firstName]; if (![allResults containsObject:fullName]) [allResults addObject:fullName]; CFRelease(record); [firstName release]; [lastName release]; } CFRelease(addressBook); [people release]; [/sourcecode]