Address Book Tutorial in iOS
In this Address Book Tutorial in iOS, learn how to add and edit contacts in a fun app about pets. By Evan Dekhayser.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Address Book Tutorial in iOS
20 mins
Although Objective C is an object-oriented language, not all of the frameworks you’ll use while developing for iOS are object-oriented.
Some are written in C, such as the Address Book API, which you’ll learn about in this tutorial.
The Address Book is the way you can read or modify the user’s contacts from your apps (the same contacts that show up in the Contacts app).
Because the Address Book is a C-based API, it does not use objects; instead it utilizes other types. In this Address Book tutorial, you’ll become familiar with a few of these:
- ABRecordRef: This is a contact record. It has all the properties that can be entered into the Contacts app.
- ABAddressBookRef: This is the collection of all the user’s contacts. You can modify its records, add new records, or delete a record.
- ABMutableMultiValueRef: This is the mutable version of ABMultiValueRef, though it is much more convenient. It lets you set properties of the ABRecordRef that may have multiple entries, such as phone number or email.
This Address Book tutorial assumes you are familiar with the basics of iOS development, and are comfortable with the basics of C syntax. If you are new to either of these, check out some of the other tutorials on our site.
Alright, let’s dive in and get some addresses!
Getting Started
To begin this tutorial, download the starter project that has the user interface pre-made, so you can stay focused on the Address Book part of the tutorial.
Build and run, and get ready to meet our furry little friends: Cheesy, Freckles, Maxi, and Shippo!
Open up ViewController.m. The starter app has four UIButtons that all call petTapped:
when pressed. If you look closely in the Utilities/Attributes Inspector in Main.storyboard, notice that each UIButton has a different number in its tag. This will help you distinguish which button is the one that called petTapped:
.
To use the Address Book API, you need to import the framework and headers. As of iOS 7, this is easy with the @import
keyword. Add this line to the top of ViewController.m:
@import AddressBook;
In this app, the user will press the image of one of the pets, and the pet’s contact information will be added to their address book (I’m surprised that even pets have iPhones!). Using the power of the Address Book API, you can finally contact your favorite furry friends.
Asking for Permission
In 2012, there was a controversy regarding certain apps sending a copy of the user’s Address Book to its servers. Because of the public’s response to this security breach, Apple immediately implemented security features to prevent this from happening without the user’s knowledge.
So now, whenever you want to use the Address Book, you first ask the user for permission.
Let’s try this out. In ViewController.m, add the following code inside petTapped:
- (IBAction)petTapped:(UIButton *)sender {
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusDenied ||
ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusRestricted){
//1
NSLog(@"Denied");
} else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized){
//2
NSLog(@"Authorized");
} else{ //ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined
//3
NSLog(@"Not determined");
}
}
Let’s go over this section by section:
- This checks to see if the user has either denied your app access to the Address Book in the past, or it is restricted because of parental controls. In this case, all you can do is inform the user that you can’t add the contact because the app does not have permission.
- This checks to see if the user has already given your app permission to use their Address Book. In this case, you are free to modify the Address Book however you want.
- This checks to see if the user hasn’t decided yet whether not to give permission to your app.
Build and run, and tap the cutest pet. You should see something like the following in the console:
PetBook[832:70b] Not determined
In real life when you want something, you ask. Same thing here!
So you need to request the user for access to the address book. Insert the following in section 3:
ABAddressBookRequestAccessWithCompletion(ABAddressBookCreateWithOptions(NULL, nil), ^(bool granted, CFErrorRef error) {
if (!granted){
//4
NSLog(@"Just denied");
return;
}
//5
NSLog(@"Just authorized");
});
The first parameter of this function is an ABAddressBookRef
, which you create with ABAddressBookCreateWithOptions(NULL, nil)
. The second argument is a block that executes once the user responds to your request.
Section 4 executes only if the user denies permission when your app asks. This should be treated the same way as when the ABAuthorizationStatus() == kABAuthorizationStatusDenied
.
Section 5 executes if the user gives permission for you to use the Address Book. This is the same as kABAuthorizationStatusAuthorized
.
Run the app in the simulator and tap on the weirdest looking pet. A popup will appear to request access to the Address Book:
Depending on your choice, you’ll see either “Just authorized” or “Just denied” in the console. Now, press an image again, and you’ll see the result is related to your action before: if you gave permission, it will say “Authorized”, or else it will say “Denied”.
Remove the NSLogs, they were only there so you could see the code’s behavior.
Note: To debug after each test, it might be useful to use iOS Simulator/Reset Content and Settings. This will let you see the alert that asks for permission every time you reset the settings, which will help later on.
Note: To debug after each test, it might be useful to use iOS Simulator/Reset Content and Settings. This will let you see the alert that asks for permission every time you reset the settings, which will help later on.
Next, add this code into sections 1 and 4 to tell the user that you can’t add the contact because it does not have needed permissions:
UIAlertView *cantAddContactAlert = [[UIAlertView alloc] initWithTitle: @"Cannot Add Contact" message: @"You must give the app permission to add the contact first." delegate:nil cancelButtonTitle: @"OK" otherButtonTitles: nil];
[cantAddContactAlert show];
Use iOS Simulator/Reset Content and Settings to reset your simulator, build and run, tap the ugliest pet, deny permission, and verify the dialog appears. Good job, iOS citizen!