How to add new contact to iOS Contacts (Address Book)?
Asked Answered
T

1

12

I want to save contact directly to an iOS device's Address Book programmatically.

How can I do it?

Thalia answered 22/3, 2011 at 10:1 Comment(0)
L
28

Here is a small example :

CFErrorRef error = NULL; 
NSLog(@"%@", [self description]);
ABAddressBookRef iPhoneAddressBook = ABAddressBookCreate();

ABRecordRef newPerson = ABPersonCreate();

ABRecordSetValue(newPerson, kABPersonFirstNameProperty, people.firstname, &error);
ABRecordSetValue(newPerson, kABPersonLastNameProperty, people.lastname, &error);

    ABMutableMultiValueRef multiPhone =     ABMultiValueCreateMutable(kABMultiStringPropertyType);
ABMultiValueAddValueAndLabel(multiPhone, people.phone, kABPersonPhoneMainLabel, NULL);
ABMultiValueAddValueAndLabel(multiPhone, people.other, kABOtherLabel, NULL);            
ABRecordSetValue(newPerson, kABPersonPhoneProperty, multiPhone,nil);
CFRelease(multiPhone);
    // ... 
    // Set other properties
    // ...
    ABAddressBookAddRecord(iPhoneAddressBook, newPerson, &error);

ABAddressBookSave(iPhoneAddressBook, &error);
    CFRelease(newPerson);
    CFRelease(iPhoneAddressBook);
if (error != NULL) 
{
       CFStringRef errorDesc = CFErrorCopyDescription(error);
   NSLog(@"Contact not saved: %@", errorDesc);
       CFRelease(errorDesc);        
}
Lannielanning answered 22/3, 2011 at 10:6 Comment(5)
But I have a small question,what about saving a phone number,what is the property we need to make use ofFifteen
@EshwarChaitanya Here is the complete reference heig.ch/sohi You have to search for kABPersonPhonePropertyLannielanning
@RanjitChandel Did you ask permission before creating the contact ? Here is a sample asking permission: gist.github.com/jfreyre/605a5e500eaf8a1b6610 NB: I'm not using ABAddressBookRef iPhoneAddressBook = ABAddressBookCreate(); which has been deprectated since my first answer but ABAddressBookRef iPhoneAddressBook = ABAddressBookCreateWithOptions(NULL, NULL); which is the new wayLannielanning
@Lannielanning Thank you, I missed permission part, Now is working fineToiletry
I have contact large contact list line 1000 to 2000 contact which I have to save in contact list .I make a look and start adding in contact list . but it is taking so much time . how to overcome with this problem.Menstruate

© 2022 - 2024 — McMap. All rights reserved.