iPhone Programming: Adding a Contact to the iPhone Address Book

 

Adding a contact to the iPhone’s address book isn’t horribly complicated, but it’s not the most straightforward process in the world, either, because the documentation leaves a bit to be desired. There is an Address Book Programming Guide published by Apple, but at 28 pages, it feels a bit bloated when you’re just trying to quickly figure out a simple process like this, and somewhat ironically, the “Creating a New Person” section is less than a page, and doesn’t go into much detail. The XCode documentation is helpful, but it still takes some effort to put all the pieces together, so this is basically just a walk-through of the process of creating a new contact, and adding some common fields to it.

To create a new record, we start out by creating a CFErrorRef variable that will hold any errors that get generated throughout the rest of the process. In my experience, most errors here tend to generate exceptions anyway, but there’s an error parameter, so we may as well use it. Anyway, here’s the line:

        CFErrorRef error = NULL; 

We then create our reference to the iPhone Address Book with a call to ABAddressBookCreate():

        ABAddressBookRef iPhoneAddressBook = ABAddressBookCreate();

And then we create a new person record:

        ABRecordRef newPerson = ABPersonCreate();
At this point, we haven’t saved anything to the address book yet, but we can start adding data to the person record. To do this, we use ABRecordSetValue, but some fields need to be formatted differently from others. For some, like first name and last name, we can just pass in a string:

        ABRecordSetValue(newPerson, kABPersonFirstNameProperty, @”John”, &error);
ABRecordSetValue(newPerson, kABPersonLastNameProperty, @”Doe”, &error);

kABPersonFirstNameProperty and kABPersonLastNameProperty are constants defined by Apple that specify which fields you’re saving. They’re listed in the XCode documentation under Personal Information Properties in the ABPerson Reference document. We can also set some other fields in this manner, such as company and title:

        ABRecordSetValue(newPerson, kABPersonOrganizationProperty, @”Model Metrics”, &error);
ABRecordSetValue(newPerson, kABPersonJobTitleProperty, @”Senior Slacker”, &error);

Where it gets a bit trickier is when we want to set our phone, email, or address properties, because these fields use ABMutableMultiValueRef rather than strings to store the data, and the specific data types of the values vary a bit depending on which one we’re talking about. For phone, we would do something like this:
        ABMutableMultiValueRef multiPhone = ABMultiValueCreateMutable(kABMultiStringPropertyType);
ABMultiValueAddValueAndLabel(multiPhone, @”1-555-555-5555″, kABPersonPhoneMainLabel, NULL);
ABMultiValueAddValueAndLabel(multiPhone, @”1-123-456-7890″, kABPersonPhoneMobileLabel, NULL);
ABMultiValueAddValueAndLabel(multiPhone, @”1-987-654-3210″, kABOtherLabel, NULL);
ABRecordSetValue(newPerson, kABPersonPhoneProperty, multiPhone,nil);
CFRelease(multiPhone);

The first two phone types (kABPersonPhoneMainLabel and kABPersonPhoneMobileLabel) are listed as Phone Number Properties in the ABPerson Reference, along with kABPersonPhoneHomeFAXLabel, kABPersonPhoneWorkFAXLabel, and kABPersonPhonePagerLabel. Despite the fact that the two fax numbers and the pager number seem fairly useless (you can’t send a fax from your phone, and who has a pager anymore?) but there’s nothing listed there for Other, or Work Phone or anything like that. That’s where the Generic Property labels come into play:

      kABWorkLabel;
kABHomeLabel;
kABOtherLabel;

Those will file the phone numbers as Work, Home, and Other, respectively. After adding the values to the ABMutableMultiValueRef, we need to call ABRecordSetValue, only this time instead of passing a string in for the third parameter, we pass in multiPhone. Then be sure to free up the memory with CFRelease.

Adding email addresses to the record is pretty similar to adding phone numbers, where we create an ABMutableMultiValueRef of strings:

        ABMutableMultiValueRef multiEmail = ABMultiValueCreateMutable(kABMultiStringPropertyType);
ABMultiValueAddValueAndLabel(multiEmail, @”johndoe@modelmetrics.com”, kABWorkLabel, NULL);
ABRecordSetValue(newPerson, kABPersonEmailProperty, multiEmail, &error);
CFRelease(multiEmail);

Where it gets a little different is when we go to set the street address values. While we do still use an ABMutableMultiValueRef, we won’t be using kABMultiStringPropertyType. To set the street address, we use kABMultiDictionaryPropertyType instead, so we have to create an NSMutableDictionary, and the method calls end up being a bit different:

        ABMutableMultiValueRef multiAddress = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType);

NSMutableDictionary *addressDictionary = [[NSMutableDictionary alloc] init];

            [addressDictionary setObject:@"750 North Orleans Street, Ste 601" forKey:(NSString *) kABPersonAddressStreetKey];
[addressDictionary setObject:@"Chicago" forKey:(NSString *)kABPersonAddressCityKey];
[addressDictionary setObject:@"IL" forKey:(NSString *)kABPersonAddressStateKey];
[addressDictionary setObject:@"60654" forKey:(NSString *)kABPersonAddressZIPKey];

          ABMultiValueAddValueAndLabel(multiAddress, addressDictionary, kABWorkLabel, NULL);
ABRecordSetValue(newPerson, kABPersonAddressProperty, multiAddress,&error);
CFRelease(multiAddress);

kABWorkLabel means that we’re setting this as the contact’s work address. And to add it to the contact record, we call ABRecordSetValue as before, releasing the memory afterward.

The last step is to add the new record to the address book, and save it back to the device:

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

And then we can check for any errors:

        if (error != NULL)
{

                  NSLog(@”Danger Will Robinson! Danger!”);

        }

 

So that concludes this introduction to creating new records in the address book.

Tom

rate this post

    Speak Your Mind

    *

  1. Sreelatha says:

    Hi Tom,

    Nice post from you.. I am working on editing a contact, can you pls help me in this regard, can i get a sample application for adding and editing a contact pls.

    Thanks&Regards,
    Sreelatha.

  2. Tom says:

    Hi Sreelatha,

    If you come across any specific problems with the instructions posted here, please let me know, and I’ll be happy to take a look.

    Thanks,
    Tom

  3. Manish says:

    Dear Tom,
    Nice work.god bless u dear.

  4. Sreelatha says:

    Hi Tom,

    Thank you very much.

    I had followed your code and added the contact details using a program.

    I wanted to eliminate adding duplicate records, I am able to retrieve Firstname and Lastname and compare them and take appriopriate action the problem is if 2 persons have same first name and lastname then I wanted to compare with Email property.

    1) How to retrieve the Email property, phone property details as they contain multiple values ?

    2) After adding a contact to the contact list I wanted to open the Contact list in the Edit mode so that the user can do some modifications?

    Pls. give some sample code for this.

    Thanks&Regards,
    Sreelatha.

  5. Sreelatha says:

    Hi Tom,

    I am able to retrieve the email, phone property details.

    I need the second one pls. can you pls. send me the code for second point.

    Thanks&Regards,
    Sreelatha

  6. Sreelatha says:

    Hi Tom,

    Can you pls. let me know how do I edit a selected contact from the address book using programming.

    I have tried using ABPersonViewController but it does’nt work for me can you pls. send me some sample code for this.

    It would be of great help pls.

    Thanks&Regards,
    Sreelatha.

  7. Tom says:

    Hi Sreelatha,

    I recommend reading through the iPhone Address Book Programming Guide. It should tell you everything you need to know:

    http://developer.apple.com/iphone/library/documentation/ContactData/Conceptual/AddressBookProgrammingGuideforiPhone/100-Introduction/Introduction.html

    Thanks,
    Tom

  8. Sreelatha says:

    Hi Tom,

    Thanks for your reply.

    I had gone through the AddressBookProgramming guide, I am facing some problem for opening the selected contact in the Edit mode.

    I have used ABPersonViewController and also made allowsEditing property to YES but it does not work , it does not show the selected contact in the Edit mode.

    Can you please provide me some sample.

    Thanks & Regards,
    Sreelatha.

  9. Manish says:

    plz help me

    ABMutableMultiValueRef multiAddress = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType);

    NSMutableDictionary *addressDictionary = [[NSMutableDictionary alloc] init];

    [addressDictionary setObject:@"750 North Orleans Street, Ste 601" forKey:(NSString *) kABPersonAddressStreetKey];
    [addressDictionary setObject:@"Chicago" forKey:(NSString *)kABPersonAddressCityKey];
    [addressDictionary setObject:@"IL" forKey:(NSString *)kABPersonAddressStateKey];
    [addressDictionary setObject:@"60654" forKey:(NSString *)kABPersonAddressZIPKey];

    ABMultiValueAddValueAndLabel(multiAddress, addressDictionary, kABWorkLabel, NULL);
    ABRecordSetValue(newPerson, kABPersonAddressProperty, multiAddress,&error);
    CFRelease(multiAddress);

  10. Manish says:

    plz help me

    ABMutableMultiValueRef multiAddress = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType);

    NSMutableDictionary *addressDictionary = [[NSMutableDictionary alloc] init];

    [addressDictionary setObject:@"750 North Orleans Street, Ste 601" forKey:(NSString *) kABPersonAddressStreetKey];
    [addressDictionary setObject:@"Chicago" forKey:(NSString *)kABPersonAddressCityKey];
    [addressDictionary setObject:@"IL" forKey:(NSString *)kABPersonAddressStateKey];
    [addressDictionary setObject:@"60654" forKey:(NSString *)kABPersonAddressZIPKey];

    ABMultiValueAddValueAndLabel(multiAddress, addressDictionary, kABWorkLabel, NULL);
    ABRecordSetValue(newPerson, kABPersonAddressProperty, multiAddress,&error);
    CFRelease(multiAddress);

    adding in adressbook is not working

  11. Tom says:

    Manish,

    You still need to do this to save the address book back to the device:

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

  12. Sreelatha says:

    Hi Tom,

    Can you please tell me how do I edit a contact using iPhone programming. please help me.

    Thanks & Regards,
    Sreelatha.

  13. JaneRadriges says:

    The best information i have found exactly here. Keep going Thank you

  14. Damien says:

    @Tom

    Thanks for the post, awesome info!

    @Sreelatha

    Wow! You are very demanding. Perhaps you’d like Tom to do all your programming for you?

    My advice is to check out the iTunesU Stanford lecture on editing the addressbook… it should be very enlightening. There’s a great bit on how to automatically provide person editors once you have your ABRecordRef.

    Of course, you could always continue to bug poor people like Tom to do all your grunt work for you.

    To answer what I’m sure your next question will be, just Google “Stanford itunesu iphone” and read through the results. Or just go to the iTunes Store, type in “stanford iphone”.

  15. Carl Grainger says:

    Hi Tom, just wanted to say thanks for this great work. I’ve a few books on the subject but nothing came close to this. Everything worked first time, I just working trough the API ref to sort out the last two issues:
    1. checking for duplicated contact and subsequent alert and actions (overwrite/cancel)
    2. how to add an image to the contact.
    These areas would make a great update to this piece.
    Great work.

  16. dhivya says:

    hey tom it juz worked very well without any errors gr8 work dude

  17. Arpan Desai says:

    Hi Tom,
    A Great post I must say.
    I am trying to fetch the Contacts from Address Book.
    So far, I have fetched the Multi Valued Phone Number and Email Addresses.

    I read the Address BOok reference on iPhone , but still getting error while I am trying to retrieve or fetch the particular property of Address Book . let say it is State Property or Zip Code Property.

    I am trying with the 5 or 6 contacts , any help would be great.
    If you want a post to retrieve the contacts information from address book. let Me know, I can post it any time.

    With Regards,
    Arpan

  18. iphonedev says:

    will it be possible to have a function which can sync the address book from a server
    i can pull the add book and send it
    but i am not too sure about the other part
    getting address book from the net and making entries on the iphone

  19. Tom says:

    Yes, that is possible. We do exactly that in our Search2GO app.

  20. iphonedev says:

    is this the crm app ?

  21. Tom says:

    Yes, Search2GO allows you to search Contacts, Accounts, Leads, and Opportunities in your company’s Salesforce environment.

  22. jimzhao says:

    hi, Ankit;

    add the ABPersonRef to addressbook, then save the addressbook,
    then, your ABRecordID recID=ABRecordGetRecordID(aRecord); will not return -1.

    code:
    ABAddressBookAddRecord(addressbook, aRef, (CFErrorRef*)&err);
    ABAddressBookSave(addressbook, (CFErrorRef*)&err);

  23. Tom says:

    Thanks a lot for this! This is great stuff!

    Have you any idea how to set automatically a photo?

    Cheers

    Tom

  24. Best you could change the page name title iPhone Programming: Adding a Contact to the iPhone Address Book | Model Metrics to something more catching for your webpage you write. I loved the blog post even sononetheless.

  25. Ghlwcmxl says:

    aztec symbols tattoos,

  26. Johny says:

    Hey,
    Can anybody help me with making any particular contact as read-only?
    I made an app which added few contacts to iPhone's address book. And now I want to make the contacts as read-only which I added through my App.
    Is there any way to do so?
    Johny

  27. Philip says:

    Hello.

    Thank you for a great post. It has helped me alot.
    However, i wonder if you or anyone else can help me. I'm building an app that adds persons to the adressbook. To these persons i want to add a custom label for the phone.
     I used this code to add the custom label, and in the iphone simulator the phone nr is displayed with the custom label, but in the real phone, the number is added to the home label.
         ABMutableMultiValueRef multiPhone = ABMultiValueCreateMutable(kABMultiStringPropertyType);
               
            ABMultiValueAddValueAndLabel(multiPhone, @"1-987-654-3210", @"Custom label", NULL);        
            ABRecordSetValue(newPerson, kABPersonPhoneProperty, multiPhone,nil);
            CFRelease(multiPhone);

    Any help is greatly appreciated.
    /Philip

  28. Philip says:

    Hello.
    I found the answer to my question above. The reason this happened was because i had an external contacts db (exchange server), the contact was added but it wasn't able to add the custom label. When i changed to have the iPhone as default for contacts it worked.
    Maybe this helps someone.
    /Philip

  29. Thomas says:

    Help. I am using iOS5 and xCode 4.2 and everything works accept adding the address. I get the following error in the code:
    Implicit conversion of an Objective-C pointer to 'CFTypeREF' … not allowed with ARC
    Here:
    ABMultiValueAddValueAndLabel(multiAddress, addressDictionary, kABWorkLabel, NULL);
     
    xCode does not like the addressDictionary there.

  30. Christian says:

    @Thomas:
    Had the same issue, here is the workaround:
     
    CFTypeRef ctr = CFBridgingRetain(addressDictionary);
    ABMultiValueAddValueAndLabel(multiAddress, ctr, kABWorkLabel, NULL);
    CFBridgingRelease(ctr);

  31. luffy says:

    great
    thank you very much

  32. David says:

    im new to xcode,
    Do you have this project to be downloaded.
    i have problems from the beginning,And when im adding ABAddressBookRef iPhoneAddressBook = ABAddressBookCreate(); 
    to ViewController.m
    (after adding #import <AddressBookUI/AddressBookUI.h>)
    i get error "intializer element is not a compile-time constant"
    can you add some extra instruction what to put and where
    thanks a lot
    D

  33. luca says:

    @David
    you have to include the simple framework "AddressBook" that is needed to work on the address book's database, the library you imported is useful to catch the data of the actual contacts

    I hope had helped you

  34. Abed Halawi says:

    Very helpful post! saved my day! thanks a lot…

  35. Roberto says:

    Great work and Great explanation!

    I am having a hard time adding multiple Addresses. When I add the second one it wipes out the first. Would you mind showing us how to do that?

    Code…
    for (Address *Item in NewContact.Addresses) {
    ABMutableMultiValueRef Address = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType);
    //Create a Disctionary Array to hold the address
    NSMutableDictionary *addressDictionary = [[NSMutableDictionary alloc] init];
    [addressDictionary setObject:Item.Street forKey:(NSString *)kABPersonAddressStreetKey];
    [addressDictionary setObject:Item.City forKey:(NSString *)kABPersonAddressCityKey];
    [addressDictionary setObject:Item.State forKey:(NSString *)kABPersonAddressStateKey];
    [addressDictionary setObject:Item.Zip forKey:(NSString *)kABPersonAddressZIPKey];
    [addressDictionary setObject:Item.Country forKey:(NSString *)kABPersonAddressCountryKey];
    if(Item.Type == Home)
    {
    ABMultiValueAddValueAndLabel(Address, CFBridgingRetain(addressDictionary), kABHomeLabel, NULL);
    }
    else if (Item.Type==Work)
    {
    ABMultiValueAddValueAndLabel(Address, CFBridgingRetain(addressDictionary), kABWorkLabel, NULL);
    }
    ABRecordSetValue(person, kABPersonAddressProperty, Address,&error);
    CFRelease(Address);
    }

  36. rupal says:

    its working in my application.
    its really nice… :)

Trackbacks

  1. [...] Adding a Contact to the iPhone Address Book [...]

Follow

Get every new post from our Voice blog delivered to your Inbox. Nice and simple.

Join other followers: