Posted by: bearc0025 | April 22, 2009

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...

			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];

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

Follow

Get every new post delivered to your Inbox.

Join 388 other followers

%d bloggers like this: