Search code examples
iosobjective-caddressbook

iOS Address Book: Contact name from value of NSString


I am trying to add contacts to address book from my app. The code I have works great, but I want the contact name to be the value of a NSString. I have tried to replace @"David" in the code with the name of the string, but it doesn't seem to work.

CFErrorRef error = nil;
ABAddressBookRef iPhoneAddressBook = ABAddressBookCreate();
ABRecordRef newPerson = ABPersonCreate();
ABRecordSetValue(newPerson, kABPersonFirstNameProperty,@"David", nil);
ABRecordSetValue(newPerson, kABPersonLastNameProperty,@"Olsen", nil);

//Add my phone number

ABMutableMultiValueRef phoneNumber = ABMultiValueCreateMutable(kABStringPropertyType);
ABMultiValueAddValueAndLabel(phoneNumber,
                             @"095", kABPersonPhoneMainLabel, nil);
ABRecordSetValue(newPerson, kABPersonEmailProperty, phoneNumber, nil);


//Finally saving the contact in the address book
ABAddressBookAddRecord(iPhoneAddressBook, newPerson, &error);
ABAddressBookSave(iPhoneAddressBook, &error);
if (error != NULL)
{
    NSLog(@"Saving contact failed.");
}


NSLog(@"Contact saved.");

}


Solution

  • You have to use a CFStringRef, so __bridge your NSString

    NSString *name = @David";
    ABRecordSetValue(newPerson, kABPersonFirstNameProperty,(__bridge  CFStringRef) name, nil);