10.1. Retrieving a Reference to an Address Book

Problem

You would like to work with a user’s contacts. To do this, first you need to get a reference to the user’s address book database. This reference is what you use to retrieve entries, as well as to make and save changes.

Solution

Use the ABAddressBookCreate function in the Address Book framework:

- (BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{ ABAddressBookRef addressBook = ABAddressBookCreate(); if (addressBook != nil){ NSLog(@"Successfully accessed the address book."); /* Work with the address book here */ /* Let's see if we have made any changes to the address book or not, before attempting to save it */ if (ABAddressBookHasUnsavedChanges(addressBook)){ /* Now decide if you want to save the changes to the address book */ NSLog(@"Changes were found in the address book."); BOOL doYouWantToSaveChanges = YES; /* We can make a decision to save or revert the address book back to how it was before */ if (doYouWantToSaveChanges){ CFErrorRef saveError = NULL; if (ABAddressBookSave(addressBook, &saveError)){ /* We successfully saved our changes to the address book */ } else { /* We failed to save the changes. You can now access the [saveError] variable to find out what the error is */ } } else { /* We did NOT want to save the changes to the address book so let's revert it to how it was before */ ABAddressBookRevert(addressBook); } } else { /* We have not made any changes to ...

Get iOS 5 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.