iOS 程序内将信息保存到通讯录

来源:互联网 时间:2017-01-22




2016-08-16 15_36_02.gif

导入AddressBook.framework
#import<AddressBook/AddressBook.h>
// 添加联系人(联系人名称、号码、号码备注标签)
+ (BOOL)addContactName:(NSString*)name phoneNum:(NSString*)num withLabel:(NSString*)label
{
// 创建一条空的联系人
ABRecordRef record = ABPersonCreate();
CFErrorRef error;
// 设置联系人的名字
ABRecordSetValue(record, kABPersonFirstNameProperty, (__bridge CFTypeRef)name, &error);
// 添加联系人电话号码以及该号码对应的标签名
ABMutableMultiValueRef multi = ABMultiValueCreateMutable(kABPersonPhoneProperty);
ABMultiValueAddValueAndLabel(multi, (__bridge CFTypeRef)num, (__bridge CFTypeRef)label, NULL);
ABRecordSetValue(record, kABPersonPhoneProperty, multi, &error);
ABAddressBookRef addressBook = nil;
// 如果为iOS6以上系统,需要等待用户确认是否允许访问通讯录。
if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0){
addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
//等待同意后向下执行
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error){
dispatch_semaphore_signal(sema);
});
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}else{
addressBook = ABAddressBookCreateWithOptions(NULL, (CFErrorRef *)&error);
}
// 将新建联系人记录添加如通讯录中
BOOL success = ABAddressBookAddRecord(addressBook, record, &error);
if (!success) {
return NO;
}else{
// 如果添加记录成功,保存更新到通讯录数据库中
success = ABAddressBookSave(addressBook, &error);
return success ? YES : NO;
}
}



相关阅读:
Top