adding a new number to existing ABRecord in ABAddressBook - iPhone
I am trying to update the content of an existing contact in the addressbook through my application but without the need for a UI. The scenario is like this:
1 The user enters a number and a name 2 The application checks if that name is in the contacts list 3 if it is then it checks if the number is one of the contacts for that name 4 If not it adds it to that name
I have managed to achieve steps 1-3 but i could not find a way to do 4. Can any one help?
Below if what my code looks like
...
CFIndex lTotalContactsCount = ABAddressBookGetPersonCount(lAddressBook);
NSArray *people = (NSArray *)ABAddressBookCopyArrayOfAllPeople(lAddressBook );
for (CFIndex i = 0; i < lTotalContactsCount; i++)
{
ABRecordRef lRef = (ABRecordRef)[people objectAtIndex:i];
...
// if names match
{
ABMutableMultiValueRef lPhoneNumbers = ABRecordCopyValue(lRef, kABPersonPhoneProperty);
CFIndex lContactPhoneNumberCount = ABMultiValueGetCount(lPhoneNumbers);
ABRecordID contactID = ABRecordGetRecordID(lRef);
...
// if numbers dont match
{
// THIS BIT IS NOT WOKRING
CFErrorRef error = NULL;
ABMutableMultiValueRef multiPhone = ABMultiValueCreateMutable(kABMultiStringPropertyType);
ABMultiValueAddValueAndLabel(mu开发者_如何学编程ltiPhone, number, (CFStringRef)@"Duplicate", NULL);
// ABRecordSetValue(newPerson, kABPersonFirstNameProperty, name, &error);
//add the number to the contact
ABRecordSetValue(lRef, kABPersonPhoneProperty, multiPhone,nil);
// ABAddressBookAddRecord(lAddressBook, lRef, &error);
ABAddressBookSave(lAddressBook, &error);
}
if( firstName )
CFRelease(firstName);
if( lastName )
CFRelease(lastName);
if( lPhoneNumbers )
CFRelease(lPhoneNumbers);
// no need to search other entries
if(numberExists)
break;
}
After further look this morning at the APIs i managed to find the solution. Here you go:
// contactId is the ID of the person i need to add a new number to his contacts
// got the id through : ABRecordGetRecordID( ABRecordRef )
ABRecordRef person = ABAddressBookGetPersonWithRecordID(lAddressBook, contactID);
ABMutableMultiValueRef multiPhone = ABMultiValueCreateMutableCopy(lPhoneNumbers);
ABMultiValueAddValueAndLabel(multiPhone, number, (CFStringRef)@"Duplicate", NULL);
//add the number to the contact
ABRecordSetValue(person, kABPersonPhoneProperty, multiPhone,nil);
ABAddressBookSave(lAddressBook, &error);
精彩评论