CFErrorRef error = NULL;
bool result;
//创建一个空记录
ABRecordRef person = ABPersonCreate();
//设置相关属性,后面三个方法见后
result = ABRecordSetValue(person, kABPersonOrganizationProperty, (CFStringRef)self.name, &error) &&
[AddressBookUtils addPhone:person phone:self.phoneNumber] &&
[AddressBookUtils addAddress:person street:self.address] &&
[AddressBookUtils addImage:person image:self.image];
//增加记录
result = ABAddressBookAddRecord(addressBook, person, &error);
//保存到地址本
result = ABAddressBookSave(manager.addressBook, &error);
//保存后就可以拿到id了,id没保存前是 -1
ABRecordID personId = ABRecordGetRecordID(person);
+ (BOOL)addPhone:(ABRecordRef)person phone:(NSString*)phone
{
ABMutableMultiValueRef multi = ABMultiValueCreateMutable(kABMultiStringPropertyType);
CFErrorRef anError = NULL;
// The multivalue identifier of the new value isn't used in this example,
// multivalueIdentifier is just for illustration purposes. Real-world
// code can use this identifier to do additional work with this value.
ABMultiValueIdentifier multivalueIdentifier;
if (!ABMultiValueAddValueAndLabel(multi, (CFStringRef)phone, kABPersonPhoneMainLabel, &multivalueIdentifier)){
CFRelease(multi);
return NO;
}
if (!ABRecordSetValue(person, kABPersonPhoneProperty, multi, &anError)){
CFRelease(multi);
return NO;
}
CFRelease(multi);
return YES;
}
+ (BOOL)addAddress:(ABRecordRef)person street:(NSString*)street
{
ABMutableMultiValueRef address = ABMultiValueCreateMutable(kABDictionaryPropertyType);
static int homeLableValueCount = 5;
// Set up keys and values for the dictionary.
CFStringRef keys[homeLableValueCount];
CFStringRef values[homeLableValueCount];
keys[0] = kABPersonAddressStreetKey;
keys[1] = kABPersonAddressCityKey;
keys[2] = kABPersonAddressStateKey;
keys[3] = kABPersonAddressZIPKey;
keys[4] = kABPersonAddressCountryKey;
values[0] = (CFStringRef)street;
values[1] = CFSTR("");
values[2] = CFSTR("");
values[3] = CFSTR("");
values[4] = CFSTR("");
CFDictionaryRef aDict = CFDictionaryCreate(
kCFAllocatorDefault,
(void *)keys,
(void *)values,
homeLableValueCount,
&kCFCopyStringDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks
);
// Add the street address to the person record.
ABMultiValueIdentifier identifier;
BOOL result = ABMultiValueAddValueAndLabel(address, aDict, kABHomeLabel, &identifier);
CFErrorRef error = NULL;
result = ABRecordSetValue(person, kABPersonAddressProperty, address, &error);
CFRelease(aDict);
CFRelease(address);
return result;
}
+ (BOOL)addImage:(ABRecordRef)person image:(UIImage*)image
{
CFErrorRef error = NULL;
// remove old image data firstly
ABPersonRemoveImageData(person, NULL);
// add new image data
BOOL result = ABPersonSetImageData (
person,
(CFDataRef)UIImagePNGRepresentation(image),
&error
);
// CFRelease(error);
return result;
}