Chapter 18. Address Book

The user’s address book, which the user sees through the Contacts app, is effectively a database that can be accessed directly through the Address Book framework. You’ll need to @import AddressBook. This is, unfortunately, a C API, which means that you’re going to be doing a lot of manual memory management.

A user interface for interacting with the address book is also provided, through Objective-C classes, by the Address Book UI framework. You’ll need to @import AddressBookUI.

Address Book Database

The address book is an ABAddressBookRef obtained by calling ABAddressBookCreateWithOptions. There are in fact no options to pass, so the first parameter is always nil. The important thing is the second parameter, a pointer to a CFErrorRef; if the result is nil, the CFErrorRef describes the error. The reason there can be an error is that the user can deny your app access to the address book:

CFErrorRef err = nil;
ABAddressBookRef adbk = ABAddressBookCreateWithOptions(nil, &err);
if (nil == adbk) {
    NSLog(@"error: %@", err);
    return;
}

If access has neither been denied nor granted, however, the result will not be nil, and there will be no CFErrorRef. This can be a disaster, because you are now working with an ABAddressBookRef that is non-nil but is nevertheless invalid and useless, and whatever further actions you perform involving the address book will fail. To prevent this, you should call ABAddressBookGetAuthorizationStatus to learn the current status. If it is kABAuthorizationStatusNotDetermined ...

Get Programming iOS 7, 4th Edition 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.