iOS儲存聯絡人到系統通訊錄
阿新 • • 發佈:2019-02-10
1、首先判斷當前通訊錄是否存在這個聯絡人
// 判斷通訊錄是否存在某個聯絡人
+ (BOOL)isExistContactNameByName:(NSString *)contactName{
ABAddressBookRef addBook = nil;
__block BOOL isExist = NO;
CFErrorRef error = nil;
addBook = ABAddressBookCreateWithOptions(NULL, &error);
dispatch_semaphore_t sema=dispatch_semaphore_create(0 );
// 申請許可權
ABAddressBookRequestAccessWithCompletion(addBook, ^(bool granted, CFErrorRef error) {
if (granted) {
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addBook);
CFIndex number = ABAddressBookGetPersonCount(addBook);
for (NSInteger index = 0 ; index < number; index++) {
//獲取聯絡人物件的引用
ABRecordRef people = CFArrayGetValueAtIndex(allPeople, index);
//獲取當前聯絡人名字
NSString*firstName=(__bridge NSString *)(ABRecordCopyValue(people, kABPersonFirstNameProperty));
if ([firstName isEqualToString:contactName]) {
isExist = YES ;
}
}
}
dispatch_semaphore_signal(sema);
});
//等待訊號觸發
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
return isExist;
}
2、判斷是否存在這個聯絡人且有通訊錄許可權
- (void)saveYdCallAnswerPhoneToAdrBook{
NSString *ydContactName = @"億點連線呼轉測試";
NSString *ydContactNote = @"這是億點連線的電話測試號碼";
if (![SSAdrBookHelper isExistContactNameByName:ydContactName] &&
ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
[SSAdrBookHelper createAddBookRecordByPhoneArr:self.ydPhoneArray
andTitle:ydContactName
andNote:ydContactNote];
}
}
3、存入聯絡人
// 往通訊錄新增一條新聯絡人
+ (void)createAddBookRecordByPhoneArr:(NSArray *)phoneArr andTitle:(NSString *)title andNote:(NSString *)note{
CFErrorRef error = NULL;
if (!phoneArr || !title) {return;}
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
ABRecordRef newRecord = ABPersonCreate();
ABRecordSetValue(newRecord, kABPersonFirstNameProperty, (__bridge CFTypeRef)title, &error);
//建立一個多值屬性(電話)
ABMutableMultiValueRef multi = ABMultiValueCreateMutable(kABMultiStringPropertyType);
// ABMultiValueAddValueAndLabel(multi, (__bridge CFTypeRef)obj, (__bridge CFStringRef)@"億點連線呼轉測試", NULL);
[phoneArr enumerateObjectsUsingBlock:^(NSString *phone, NSUInteger idx, BOOL * _Nonnull stop) {
// 新增手機號碼
ABMultiValueAddValueAndLabel(multi, (__bridge CFTypeRef)phone, kABPersonPhoneMobileLabel, NULL);
}];
ABRecordSetValue(newRecord, kABPersonPhoneProperty, multi, &error);
//新增email
// ABMutableMultiValueRef multiEmail = ABMultiValueCreateMutable(kABMultiStringPropertyType);
// ABMultiValueAddValueAndLabel(multiEmail, (__bridge CFTypeRef)([self.infoDic objectForKey:@"email"]), kABWorkLabel, NULL);
// ABRecordSetValue(newRecord, kABPersonEmailProperty, multiEmail, &error);
// 新增備註
ABRecordSetValue(newRecord, kABPersonNoteProperty, (__bridge CFTypeRef)note, &error);
//新增記錄到通訊錄操作物件
ABAddressBookAddRecord(addressBook, newRecord, &error);
//儲存通訊錄操作物件
ABAddressBookSave(addressBook, &error);
CFRelease(multi);
CFRelease(newRecord);
CFRelease(addressBook);
}
效果如下: