How to add a Contact to the iPhone Address Book


Adding a contact to the iPhone we need to use AddressBook Framework in the iOS SDK. AddressBook Framework allow us to get access to the people’s contact information including personal information.

In this tutorial we are going to create and save new contact with some personal information and save in address book database.

  1. First create the reference to the ABAddressBookRef by calling ABAddressBookCreate() method.
    • CFErrorRef error = NULL;
    • ABAddressBookRef  iPhoneAddressBook = ABAddressBookCreate();
  2. Create a new person record by calling ABPersonCreate() method.
    • ABRecordRef newPerson = ABPersonCreate();
  3. Now start adding data to person object that we created in step-2. Set person’s first name, last name, nick name, organisation name , title and others by calling relevant property name.
    • ABRecordSetValue(newPerson, kABPersonFirstNameProperty, (__bridge CFTypeRef)(@”Milan”), &error); // First name 
      ABRecordSetValue(newPerson, kABPersonLastNameProperty, (__bridge CFTypeRef)(@”Panchal”), &error); // Last name 
      ABRecordSetValue(newPerson, kABPersonNicknameProperty, (__bridge CFTypeRef)(@”SAM”), &error); // nick name 
  4. To set person’s phone, email, or address properties we need to use ABMutableMultiValueRef field. You can also store Social networks, URLs and image
    • ABMutableMultiValueRef multiEmail = ABMultiValueCreateMutable(kABMultiStringPropertyType);
      ABMultiValueAddValueAndLabel(multiEmail, (__bridge CFTypeRef)(@”example@gmail.com”), kABHomeLabel, NULL);
      ABRecordSetValue(newPerson, kABPersonEmailProperty, multiEmail, &error);
  5. Finally add record in database and save the AddressBook object.
    • ABAddressBookAddRecord(iPhoneAddressBook, newPerson, &error);
    • ABAddressBookSave(iPhoneAddressBook, &error);

Following is the method to save contact information in address book. Method will save person’s first-name, last-name, nick-name, organization, image, email addresses, social networks, and URLs

- (IBAction)saveContactToAddressBook {

    CFErrorRef error = NULL;

    ABAddressBookRef iPhoneAddressBook;

    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"6.0")){
        iPhoneAddressBook = ABAddressBookCreateWithOptions(NULL, NULL);
        dispatch_semaphore_t sema = dispatch_semaphore_create(0);
        ABAddressBookRequestAccessWithCompletion(iPhoneAddressBook,  ^(bool granted, CFErrorRef error){
            dispatch_semaphore_signal(sema);
        });

        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);

    } else {
        iPhoneAddressBook = ABAddressBookCreate();
    }

    ABRecordRef newPerson = ABPersonCreate();

    // First Name - Last Name - Nickname - Company Name
    ABRecordSetValue(newPerson, kABPersonFirstNameProperty, @"Milan", &error);
    ABRecordSetValue(newPerson, kABPersonLastNameProperty, @"Panchal", &error);
    ABRecordSetValue(newPerson, kABPersonNicknameProperty, @"SAM", &error);
    ABRecordSetValue(newPerson, kABPersonOrganizationProperty, @"Pantech", &error);

    //  Add Emial addresses
    NSArray *emailAddresses = @[@"example@gmail.com"];
    ABMutableMultiValueRef multiEmail =ABMultiValueCreateMutable(kABMultiStringPropertyType);
    for (NSString *email in emailAddresses) {
        ABMultiValueAddValueAndLabel(multiEmail, email, kABHomeLabel, NULL);
    }
    ABRecordSetValue(newPerson, kABPersonEmailProperty, multiEmail, &error);
    CFRelease(multiEmail);

    //  Adding social and Skype
    ABMultiValueRef social = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType);

    NSDictionary *skype = [NSDictionary dictionaryWithObjectsAndKeys:
                           (NSString *)kABPersonInstantMessageServiceSkype,
                           kABPersonInstantMessageServiceKey,
                           @"milan_panchal24",
                           kABPersonInstantMessageUsernameKey,
                           nil];

    NSDictionary *twitter = [NSDictionary dictionaryWithObjectsAndKeys:
                             (NSString *)kABPersonSocialProfileServiceTwitter,
                             kABPersonSocialProfileServiceKey,
                             @"milan_panchal24",
                             kABPersonSocialProfileUsernameKey,
                             nil];

    NSDictionary *facebook = [NSDictionary dictionaryWithObjectsAndKeys:
                              (NSString *)kABPersonSocialProfileServiceFacebook,
                              kABPersonSocialProfileServiceKey,
                              @"MilanPantech",
                              kABPersonSocialProfileUsernameKey,
                              nil];

    NSDictionary*linkedin = [NSDictionary dictionaryWithObjectsAndKeys:
                             (NSString *)kABPersonSocialProfileServiceLinkedIn,
                             kABPersonSocialProfileServiceKey,
                             @"milanpanchal",
                             kABPersonSocialProfileUsernameKey,
                             nil];

    ABMultiValueAddValueAndLabel(social,
                                 (__bridge CFTypeRef)(skype),
                                 kABPersonInstantMessageServiceSkype, NULL); 

    ABMultiValueAddValueAndLabel(social,
                                 (__bridge CFTypeRef)(twitter),
                                 kABPersonSocialProfileServiceTwitter, NULL); 

    ABMultiValueAddValueAndLabel(social,
                                 (__bridge CFTypeRef)(facebook),
                                 kABPersonSocialProfileServiceFacebook, NULL); 

    ABMultiValueAddValueAndLabel(social,
                                 (__bridge CFTypeRef)(linkedin),
                                 kABPersonSocialProfileServiceLinkedIn, NULL); 

    ABRecordSetValue(newPerson, kABPersonSocialProfileProperty, social, &error);

    // Add an image
    NSData *dataRef = UIImagePNGRepresentation([UIImage imageNamed:@"image.png"]);
    ABPersonSetImageData(newPerson, (__bridge CFDataRef)dataRef, &error);

    // URL
    NSArray * blogUrls = @[@"http://www.techfuzionwithsam.wordpress.com",
                           @"http://www.mypoemswithsam.wordpress.com"];

    ABMutableMultiValueRef urlMultiValue = ABMultiValueCreateMutable(kABStringPropertyType);
    for (NSString *blogUrl in blogUrls) {
        ABMultiValueAddValueAndLabel(urlMultiValue, (__bridge CFTypeRef)(blogUrl), kABPersonHomePageLabel, NULL);
    }

    ABRecordSetValue(newPerson, kABPersonURLProperty, urlMultiValue, &error);
    CFRelease(urlMultiValue);

    ABAddressBookAddRecord(iPhoneAddressBook, newPerson, &error);
    ABAddressBookSave(iPhoneAddressBook, &error);

    if (error != NULL) {

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
                                                        message:@"Could not create unknown user"
                                                       delegate:nil
                                              cancelButtonTitle:@"Cancel"
                                              otherButtonTitles:nil];
        [alert show];
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Added Successfully!"
                                                        message:[NSString stringWithFormat:@"%@ was added to your contact successfully.",@"Milan Panchal"]
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
    }

    CFRelease(newPerson);
    CFRelease(iPhoneAddressBook);
}

Click here to download source code.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s