How to edit a contact?
Is there any way to edit a contact programmatically 开发者_运维技巧in the iPhone? For example, I want to modify a contact which is returned by ABPeoplePickerNavigationController
. How can I do this? I have:
(BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
NSString *phoneNum = @"01234567890";
ABAddressBookRef addressBook = ABAddressBookCreate();
contact = ABAddressBookGetPersonWithRecordID(addressBook, ABRecordGetRecordID(person));
if(phoneNum && contact != NULL)
{
ABMutableMultiValueRef phoneNumberMultiValue = ABMultiValueCreateMutable(kABMultiStringPropertyType);
ABMultiValueAddValueAndLabel(phoneNumberMultiValue, phoneNum, kABPersonPhoneMobileLabel, NULL);
[self dismissModalViewControllerAnimated:YES];
ABRecordSetValue(contact, kABPersonPhoneProperty, phoneNumberMultiValue, nil);
//THIS CODE IS NOT BEHAVING AS I EXPECTED,
//if(ABAddressBookHasUnsavedChanges(addressBook))//Anyway this needs to be checked
{
ABAddressBookSave(addressBook, NULL);
}
}
return NO;
}
The call to ABAddressBookSave(addressBook, NULL);
is working. But the problem is, all the old information of the "contact" is removed from the address book and only the "phoneNum" is saved at the end.
How can I solve this problem?
Apologies for the previous answer - I read the question wrong...! I thought that the contact wasn't saving at all on the address book.
It seems that the only information lost is the contact's other phone numbers, correct? Meaning that the ABRecordRef's other details, such as address, notes, birthdates, etc. remain intact.
If this is correct, I assume that the only feasible way to counter this deletion of other phone numbers is to simply append a PhoneLabel to the contact's existing kABPersonPhoneProperty. Instead of creating a new ABMutableMultiValueRef for the phone numbers, copy it from the record like so:
ABMutableMultiValueRef phoneNumberMultiValue = ABMultiValueCreateMutableCopy((ABMultiValueRef)ABRecordCopyValue(contact, kABPersonPhoneProperty));
With this, you can now append the new phone number with the same code:
ABMultiValueAddValueAndLabel(phoneNumberMultiValue, phoneNum, kABPersonPhoneMobileLabel, NULL);
What's neat about this is that no replacing or deletion occurs - the app simply adds another phone number to the contact's phone numbers property. :D
Hope this helps.
The first thing you should do is pass in a reference to a CFErrorRef as the second argument to ABAddressBookSave; it may be that it's trying to report an error, but unable to, since you don't give it this argument.
Currently there is no way to EDIT and SAVE the contact to the address book. The IPhone API does not support this requirement. In order to EDIT a specific contact we need to get a reference of that contact by record ID and copy all the information to the reference and then save that contact to the address book.
精彩评论