Last active
March 8, 2016 09:03
-
-
Save keitaito/fd2fe28deb48c71b487a to your computer and use it in GitHub Desktop.
Update a record's address in address book using ABAddressBook framework.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Prepare address values. These values will be saved in a record in iPhone's address book. | |
NSString *city = @"Yokohama"; | |
NSString *state = @"Kanagawa" | |
NSString *country = @"Japan"; | |
// Get a record ID. | |
ABRecordID recordID = self.recordID; // Assume you have a recordID. | |
// Create dictionary for address. | |
ABMutableMultiValueRef address = ABMultiValueCreateMutable(kABMultiDictionaryPropertyType); | |
// Set up keys and values for the dictionary. | |
CFStringRef keys[3]; | |
CFStringRef values[3]; | |
keys[0] = kABPersonAddressCityKey; | |
keys[1] = kABPersonAddressStateKey; | |
keys[2] = kABPersonAddressCountryKey; | |
values[0] = (__bridge CFStringRef)city; | |
values[1] = (__bridge CFStringRef)state; | |
values[2] = (__bridge CFStringRef)country; | |
// Create dictionary. | |
CFDictionaryRef aDict = CFDictionaryCreate(kCFAllocatorDefault, | |
(void *)keys, | |
(void *)values, | |
3, | |
&kCFCopyStringDictionaryKeyCallBacks, | |
&kCFTypeDictionaryValueCallBacks); | |
// Add the street address to the multi value. | |
ABMultiValueIdentifier identifier; | |
bool didAdd = ABMultiValueAddValueAndLabel(address, aDict, kABHomeLabel, &identifier); | |
if (!didAdd) { | |
NSLog(@"Failed to add new values to the record. New values dictionary: %@", aDict); | |
} | |
// Get a person record from addressBook. | |
ABAddressBookRef addressBook = ABAddressBookCreate(); | |
ABRecordRef person = ABAddressBookGetPersonWithRecordID(addressBook, recordID); | |
// Set multi value to the record. | |
CFErrorRef setError = NULL; | |
bool didSet = ABRecordSetValue(person, kABPersonAddressProperty, address, &setError); | |
if (!didSet) { | |
CFStringRef errorDesc = CFErrorCopyDescription(setError); | |
NSLog(@"Error: %@", errorDesc); | |
CFRelease(errorDesc); | |
} | |
// Save changes in address book. | |
bool wantToSaveChanges = YES; | |
bool didSave; | |
CFErrorRef saveError = NULL; | |
if (ABAddressBookHasUnsavedChanges(addressBook)) { | |
if (wantToSaveChanges) { | |
didSave = ABAddressBookSave(addressBook, &saveError); | |
if (!didSave) { | |
CFStringRef errorDesc = CFErrorCopyDescription(saveError); | |
NSLog(@"Error: %@", errorDesc); | |
CFRelease(errorDesc); | |
} | |
} else { | |
ABAddressBookRevert(addressBook); | |
} | |
} | |
CFRelease(aDict); | |
CFRelease(address); | |
CFRelease(addressBook); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment