Address Book tutorial for iPhone – Part 1

The Address Book technology for iOS provides a way to store people’s contact information and other personal information in a centralized database, and to share this information between applications. On an iOS device, the contacts application allows users to manage their contacts. The AddressBook Framework in the SDK allows us to get access to the address book database on the device. In this tutorial we get the name and email addresses of some persons out of the address book. The address book framework has several features.

• The Address Book framework provides access to the contact information.

• The Address Book UI framework provides the user interface to display the information.

• The Address Book database stores the information.

• The Contacts application provides a way for users to access their contact information.

Open Xcode and create a new Single View Application. For product name, use AddressBook and then fill out the Organisation Name, Company Identifier and Class Prefix fields with your customary values. Make sure only iPhone is selected in Devices, and that the Use Storyboards is deselected and Use Automatic Reference Counting checkboxes are selected (Unit Tests will not be necessary for this project). First we are going to add some test contacts into the address book. Open the simulator with XCode -> Open Developer Tool -> iOS Simulator and start the Contacts app. Create the following contacts and fill in the following attributes:

• Firstname: Steve
Lastname: Jackson
Home Email: [email protected]
Work Email: [email protected]

• Firstname: Alex
Lastname: Johnson
Home Email: [email protected]
Work Email: [email protected]

• Firstname: John
Lastname: Smith
Home Email: [email protected]
Work Email: [email protected]




In this tutorial of course we need the AddressBook FrameWork, In the project options add this framework to the project.





We are going to create a table view, which displays the full names if all contacts in the address book. When the user selects this contact, the detailed properties of the contact are displayed. Right now, let’s create the necessary pieces to display a table view. In AppDelegate.m we add a Navigation Controller. change application: didFinishLaunchingWithOptions in:

- (BOOL)application:(UIApplication *)application 
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{     
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] 
bounds]];
     // Override point for customization after application launch.     
self.viewController = [[ViewController alloc] 
initWithNibName:@"ViewController" bundle:nil];       
   
UINavigationController *navController = [[UINavigationController alloc]
 initWithRootViewController:self.viewController];
     self.window.rootViewController = navController;
     [self.window makeKeyAndVisible];          

return YES; 

}



In ViewController.xib drag a table view onto the view.


Make the following connections.


In ViewController.h we must conform our ViewController with the UITableViewDataSource and UITableViewDelegate protocol. So Open ViewController.h file and modify it to allow table view protocol. Now Create an array to put our persons data in later on.

@interface ViewController () <UITableViewDataSource, UITableViewDelegate>  
@property (nonatomic, strong) NSMutableArray *tableData;

Open viewDidLoad method of ViewController.m file and add the following lines of code. Also Implement data source and delegate protocols.

- (void)viewDidLoad
 {     
[super viewDidLoad];          
self.title = @"Contacts";          
self.tableData = [[NSMutableArray alloc] init];          
[self getPersonOutOfAddressBook];
 }  
- (NSInteger)tableView:(UITableView *)tableView 
numberOfRowsInSection:(NSInteger)section 
{     
return [self.tableData count]; 
}  
- (UITableViewCell *)tableView:(UITableView *)tableView
 cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *cellIdentifier = @"Identifier"; 

         UITableViewCell *cell = [tableView 
dequeueReusableCellWithIdentifier:cellIdentifier];

          if (cell == nil) {  
       cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
reuseIdentifier:cellIdentifier];
     } 
         Person *person = [self.tableData objectAtIndex:indexPath.row];

          cell.textLabel.text = person.fullName;

          return cell;
 } 

 - (void)tableView:(UITableView *)tableView 
didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{  
   Person *person = [self.tableData objectAtIndex:indexPath.row];

      ContactViewController *contactViewController = [[ContactViewController
 alloc] initWithPerson:person];
     [self.navigationController pushViewController:contactViewController
 animated:YES];
 }

We need a data model to put the attributes from our address book. For that create a new file. Name it Person and make it a subclass of NSObject. Open Person.h and add the following properties.

@property (nonatomic, strong) NSString *firstName; 
@property (nonatomic, strong) NSString *lastName; 
@property (nonatomic, strong) NSString *fullName; 
@property (nonatomic, strong) NSString *homeEmail; 
@property (nonatomic, strong) NSString *workEmail;

In ViewController.m we import the AddressBook framework and the Person object.

#import "Person.h" 
#import <AddressBook/AddressBook.h>

We create a new method getPersonOutOfAddressBook where our most important actions take place.

- (void)getPersonOutOfAddressBook
 {     
CFErrorRef error = NULL;

          ABAddressBookRef addressBook =
 ABAddressBookCreateWithOptions(NULL, &error);
          if (addressBook != nil)
     {   
      NSLog(@"Succesful.");  

                NSArray *allContacts = (__bridge_transfer NSArray 
*)ABAddressBookCopyArrayOfAllPeople(addressBook);   
               NSUInteger i = 0;    
     for (i = 0; i < [allContacts count]; i++)
         {      
       Person *person = [[Person alloc] init];           

               ABRecordRef contactPerson = (__bridge ABRecordRef)allContacts[i]; 
                         NSString *firstName = (__bridge_transfer NSString 
*)ABRecordCopyValue(contactPerson, kABPersonFirstNameProperty);             
NSString *lastName =  (__bridge_transfer NSString 
*)ABRecordCopyValue(contactPerson, kABPersonLastNameProperty);             
NSString *fullName = [NSString stringWithFormat:@"%@ %@",
 firstName, lastName];                          

person.firstName = firstName;             
person.lastName = lastName;             
person.fullName = fullName;             
             
//email             
ABMultiValueRef emails = ABRecordCopyValue(contactPerson, 
kABPersonEmailProperty);                          
NSUInteger j = 0;             
for (j = 0; j < ABMultiValueGetCount(emails); j++)             
{                 
NSString *email = (__bridge_transfer NSString 
*)ABMultiValueCopyValueAtIndex(emails, j);                 
if (j == 0)                 
{                     
person.homeEmail = email;                 
NSLog(@"person.homeEmail = %@ ", person.homeEmail);                 
}                              
else if (j==1)                     
person.workEmail = email;
             }           

               [self.tableData addObject:person];         
     }     
  }          

CFRelease(addressBook); 
}


A lot is going on here in this method. Let’s walk through the different parts

1. In case of an error we create an error object. We get a reference to the user’s address book.

2. we copy all contacts from the addressbook in an array.

3. We loop through the contacts in the address book. For each contact, we create a Person Object.

4. We copy the firstname and secondname properties to a NSString and concatenate the strings to the fullname, which we will diplay in our table view later on. The names are assigned to the Person object.

5. The email property of the addressbook is assigned to a multivalue reference

6. because there are multiple emails we loop through each of them and we assign them to the Personobject

7. Each person object is added to the tableData array

8. when we are done with the address book it can be released

9. When something went wrong the error is logged.

Now Build and Run the code, you should see all Contact’s full names in the table view.
(SS_5)
Now let’s create the contacts view. Add a new File. Name it ContactViewController and make it a subclass of ViewController. Also check the “With XIB for user interface” checkbox.
Open ContactViewController.xib and drag the following Labels to the view so it looks like this.
(SS_6)
Now open ContactViewController.h file and modify it as follows.

#import <UIKit/UIKit.h> 
#import "Person.h"  
@interface ContactViewController : UIViewController  
@property (nonatomic, strong) Person *person; 
@property (nonatomic, strong) NSString *firstName; 
@property (nonatomic, strong) NSString *lastName; 
@property (nonatomic, strong) NSString *homeEmail; 
@property (nonatomic, strong) NSString *workEmail;  

- (id)initWithPerson:(Person *)person;  

@end



In contactViewController.m add the following outlet properties.

@interface ContactViewController ()  

@property (nonatomic, strong) IBOutlet UILabel *firstNameLabel; 
@property (nonatomic, strong) IBOutlet UILabel *lastNameLabel; 
@property (nonatomic, strong) IBOutlet UILabel *homeEmailLabel; 
@property (nonatomic, strong) IBOutlet UILabel *workEmailLabel;  

@end



Implement the initWithPerson method. This method will be called when the view will be created. The data from our Person Object will be assigned to the ContactViewController’s properties.

- (id)initWithPerson:(Person *)person 
{     

self = [super initWithNibName:@"ContactViewController" bundle:nil];     
if (self) {         
_firstName = [person.firstName copy];         
_lastName = [person.lastName copy];         
_homeEmail = [person.homeEmail copy];         
_workEmail = [person.workEmail copy];     
}     
return self; 
}


Go back to ContactViewController.xib and make the following connections
(SS_7)
In ViewController.m import the ContactViewController also implement the tableview:didSelectRowAtIndexPath as follows.

#import "ContactViewController.h"  

- (void)tableView:(UITableView *)tableView 
didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{  
   Person *person = [self.tableData objectAtIndex:indexPath.row];      

ContactViewController *contactViewController = [[ContactViewController 
alloc] initWithPerson:person];     
[self.navigationController pushViewController:contactViewController 
animated:YES]; 
}</br>

When the users select a User’s name in the table view, the contactViewController is initialized and the person object is sent along. The contactViewController is then pushed on the navigation’s stack. Now Build and Run the code, when you select a name you should see the following view.

Leave a Reply

Your email address will not be published. Required fields are marked *