Add Contacts to the Address Book in iOS7

The AddressBook framework in iOS 7 allows you to interact with the address book database on the device. You can get the accounts properties of the user’s address book, insert and change values, and much more. In this tutorial we will insert a contact in the address book.

For retrieving values out of the address book, i refer to this tutorial.

Open Xcode and create a new Single View Application. For product name, use iOS7AddressBookTutorial and then fill out the Organization Name, Company Identifier and Class Prefix fields with your customary values. Make sure only iPhone is selected in Devices.

Go to the Storyboard and drag two labels to the main View. Give them a title of "First Name" and "Last Name". Next, drag two textField  to the main view and place them to the right of the labels. Next, drag a button to the main view and give it a title of "Add Contact".The storyboard should look like this.

Select the Assistant Editor and open ViewController.m. Ctrl and drag from the topright text field to the @interface section and create the following outlet

Repeat this step for the bottom right text field

Next, ctrl and drag from the button to the @interface section and create the following Action

In our tutorial we need to fill in some names in the textfield. However, currently when you run the application the keyboard will not dismiss when pressing enter. Let;s fix that. Make our view controller conform to the UITextViewDelegate protocol by changing the @interface line to

@interface ViewController () <UITextFieldDelegate>

Change the viewDidLoad method to

- (void)viewDidLoad
{
[super viewDidLoad];

self.firstNameField.delegate = self;
self.lastNameField.delegate = self;
}

Next, add the textFieldShouldReturn delegate method

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];

return YES;
}

When the Enter key is pressed the keyboard should be dismissed. Next, implement our addContact IBAction method

- (IBAction)addContact:(UIButton *)sender
{
ABAddressBookRef addressBook = NULL;
CFErrorRef error = NULL;

switch (ABAddressBookGetAuthorizationStatus()) {
case kABAuthorizationStatusAuthorized: {
addressBook = ABAddressBookCreateWithOptions(NULL, &error);

[self addAccountWithFirstName:self.firstNameField.text lastName:self.lastNameField.text inAddressBook:addressBook];

if (addressBook != NULL) CFRelease(addressBook);
break;
}
case kABAuthorizationStatusDenied: {
NSLog(@"Access denied to address book");
break;
}
case kABAuthorizationStatusNotDetermined: {
addressBook = ABAddressBookCreateWithOptions(NULL, &error);
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
if (granted) {
NSLog(@"Access was granted");
[self addAccountWithFirstName:self.firstNameField.text lastName:self.lastNameField.text inAddressBook:addressBook];
}
else NSLog(@"Access was not granted");
if (addressBook != NULL) CFRelease(addressBook);
});
break;
}
case kABAuthorizationStatusRestricted: {
NSLog(@"access restricted to address book");
break;
}
}
}

Our application wants to get access to the address book, which requires the user to grant the application access. We will call the  ABAddressBookGetAuthorizationStatus function to get the current status. When the status is not determined yet, the application will ask if the user alllows access to the addressbook

When the status is authorized an addressbook reference object is created and the addAccountWithFirstName:lastName:inAddressBook method will be called with the content of our textfield as parameters. Let's implement this method

- (ABRecordRef)addAccountWithFirstName:(NSString *)firstName lastName:(NSString *)lastName inAddressBook:(ABAddressBookRef)addressBook
{
ABRecordRef result = NULL;
CFErrorRef error = NULL;

//1
result = ABPersonCreate();
if (result == NULL) {
NSLog(@"Failed to create a new person.");
return NULL;
}

//2
BOOL couldSetFirstName = ABRecordSetValue(result, kABPersonFirstNameProperty, (__bridge CFTypeRef)firstName, &error);
BOOL couldSetLastName = ABRecordSetValue(result, kABPersonLastNameProperty, (__bridge CFTypeRef)lastName, &error);

if (couldSetFirstName && couldSetLastName) {
NSLog(@"Successfully set the first name and the last name of the person.");
} else {
NSLog(@"Failed.");
}

//3
BOOL couldAddPerson = ABAddressBookAddRecord(addressBook, result, &error);

if (couldAddPerson) {
NSLog(@"Successfully added the person.");
} else {
NSLog(@"Failed to add the person.");
CFRelease(result);
result = NULL;
return result;
}

//4
if (ABAddressBookHasUnsavedChanges(addressBook)) {
BOOL couldSaveAddressBook = ABAddressBookSave(addressBook, &error);

if (couldSaveAddressBook) {
NSLog(@"Succesfully saved the address book.");
} else {
NSLog(@"Failed.");
}
}

return result;
}

This is a lot of code. Let's get over each section

- 1. The ABPersonCreate function creates a new account record. 

-2. With ABRecordSetValue we set the firstName and lastName property of the record.

-3. With the ABAddressBookAddRecord function we add the record to the addressbook.

-4. With the ABAddressBookSave we will save unsaved changed to the address book database.

That's it. Build and Run the application and fill in a first and last name. Press the Add Account button. 

Go to the Contacts app to view the address book. Our newly added account should be displayed.

You can download the source code of the iOS7AddressBookTutorial at the ioscreator repository on github.