Can i edit an existing contact from ABaddressBook without ABPersonViewController?

406 views Asked by At

I have created a custom address book that copy the native address book list with contacts. Now, in detail view controller I managed to ADD a new contact and REMOVE an existing contact from native address book. I want to edit an existing contact and save changes to native address book.

1

There are 1 answers

0
Reinhard Männer On

The following example assumes that you have the ID of the record that you want to change in recordID, and that you want to change its address to a new one stored in addressDictionary.

CFErrorRef error = nil;
const ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions (NULL, &error);
if (addressBookRef != nil) {
    ABRecordRef record = ABAddressBookGetPersonWithRecordID(addressBookRef, recordID);
    if (record != nil) {
        ABMultiValueRef addressesRef = ABRecordCopyValue(record, kABPersonAddressProperty);
        if (addressesRef != nil) {
            // Addresses found
            ABMutableMultiValueRef tmpAddressesRef = ABMultiValueCreateMutableCopy(addressesRef);
            if (tmpAddressesRef != nil) {
                CFIndex addressIndex = ABMultiValueGetIndexForIdentifier (addressesRef,addressID);
                bool OK;
                OK = ABMultiValueReplaceValueAtIndex(tmpAddressesRef, (__bridge CFTypeRef)addressDictionary, addressIndex);
                if (OK) {
                    OK = ABRecordSetValue(record, kABPersonAddressProperty, tmpAddressesRef, &error);
                    if (OK) {
                        OK = ABAddressBookSave(addressBookRef, &error);
                        if (OK) {
                            // Do something
                        } else {
                            // Could not save address book
                        }
                    } else {
                        // Could not store modified address
                    }
                }
                else {
                    // Could not replace address
                }
                CFRelease(tmpAddressesRef);
            } // Mutable copy of addresses could be created
            else {
                // Could not create mutable copy of addresses
            }
            CFRelease(addressesRef);
        } else {
            // Did not find addresses
        }
    } else {
        // Could not read record
    }
    CFRelease(addressBookRef);
}
else {
    // Could not open address book
}