Address Book iOS : Contact name from string

216 Views Asked by At

I am trying to automatically add contact to the iOS address book from my app, where the name of the contact is from a NSString. I have tried to figure it out (see code under), but It didn't work. It works to add contacts with the first code I have provided (I have the save code and stuff), but I would like to add contact from string that may vary, not just a name that can't.

ABRecordRef newPerson = ABPersonCreate();
ABRecordSetValue(newPerson, kABPersonFirstNameProperty,@"Davis11", &error);
ABRecordSetValue(newPerson, kABPersonLastNameProperty, @"Scott", &error);

I have also tried this code, with no luck:

ABRecordRef newPerson = ABPersonCreate();
ABRecordSetValue(newPerson, kABPersonFirstNameProperty,fName, &error);
ABRecordSetValue(newPerson, kABPersonLastNameProperty, lName, &error);
1

There are 1 best solutions below

1
On

What you are doing is fine, but you have forgotten to call ABAddressBookAddRecord and ABAddressBookSave. Nothing will happen until you do that. What you've got is a person floating around loose. You have to put that person into the address book if you want it to be part of the address book.

Also, please remember to do memory management. Here's a complete example (but error checking is omitted from the example! do not do that in real life):

CFErrorRef err = nil;
ABAddressBookRef adbk = ABAddressBookCreateWithOptions(nil, &err);
ABRecordRef snidely = ABPersonCreate();
ABRecordSetValue(snidely, kABPersonFirstNameProperty, @"Snidely", nil);
ABRecordSetValue(snidely, kABPersonLastNameProperty, @"Whiplash", nil);
ABAddressBookAddRecord(adbk, snidely, nil);
ABAddressBookSave(adbk, nil);
if (snidely) CFRelease(snidely);
if (adbk) CFRelease(adbk);