1.添加或删除通讯录,无需跳转到通信录界面数组
/** 添加通信录 */ + (void)requestAddRLNumIntoContact { if ([self isExistContactRLNum]) { debugLog(@"联系人已存在"); }else{ [self createRLNum]; } } /**访问通信录而且检查是否联系已存在*/ + (BOOL)isExistContactRLNum { //记录用户是否容许咱们访问通信录 int __block tip = 0; BOOL __block isExist = NO; //声明通信簿 ABAddressBookRef addBook = nil; //受权 CFErrorRef error = NULL; addBook = ABAddressBookCreateWithOptions(NULL, &error); //建立初始信号量为0的信号,实现NSOperation的依赖关系 dispatch_semaphore_t sema = dispatch_semaphore_create(0); //申请访问权限 ABAddressBookRequestAccessWithCompletion(addBook, ^(bool granted, CFErrorRef error) { if (!granted) {//用户不容许 tip=1; dispatch_async(dispatch_get_main_queue(), ^{ popAlertView *popView = [[popAlertView alloc] initWithNib:[UIImage imageNamed:@"smart_success_"] tipsLabStr:@"是否容许请求访问你的通信录" tipsBtnStr:@"肯定"]; [popView.showBtn addTarget:self action:@selector(ensurePushContacts) forControlEvents:UIControlEventTouchUpInside]; [popView show]; }); }else{ //获取联系人的数组 CFArrayRef allLinkPeople = ABAddressBookCopyArrayOfAllPeople(addBook); //获取联系人总数 CFIndex number = ABAddressBookGetPersonCount(addBook); //进行遍历 for (NSInteger i = 0; i < number; i++) { //获取单个联系人对象 ABRecordRef people = CFArrayGetValueAtIndex(allLinkPeople, i); //获取联系人名字 NSString *firstName = (__bridge NSString *)(ABRecordCopyValue(people, kABPersonFirstNameProperty)); if ([firstName isEqualToString:@"智慧办公"]) { isExist = YES; } } } if (tip) { dispatch_async(dispatch_get_main_queue(), ^{ popAlertView *popView = [[popAlertView alloc] initWithNib:[UIImage imageNamed:@"smart_success_"] tipsLabStr:@"是否容许请求访问你的通信录" tipsBtnStr:@"肯定"]; [popView.showBtn addTarget:self action:@selector(ensurePushContacts) forControlEvents:UIControlEventTouchUpInside]; [popView show]; }); isExist = YES; } //发送一次信号 dispatch_semaphore_signal(sema); }); //等待信号触发 dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER); return isExist; } /**添加通信录*/ + (void)createRLNum { CFErrorRef error = NULL; //建立一个通信录操做对象 ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error); //建立一条新的联系人记录 ABRecordRef newRecord = ABPersonCreate(); //为新联系人记录添加属性值 ABRecordSetValue(newRecord, kABPersonFirstNameProperty, (__bridge CFTypeRef)(@"智慧办公"), &error); //建立一个多值属性(电话) ABMutableMultiValueRef multi = ABMultiValueCreateMutable(kABMultiStringPropertyType); ABMultiValueAddValueAndLabel(multi, (__bridge CFTypeRef)(@"02096911328"), kABPersonPhoneMobileLabel, NULL); ABRecordSetValue(newRecord, kABPersonPhoneProperty, multi, &error); //添加记录到通信录操做对象 ABAddressBookAddRecord(addressBook, newRecord, &error); //保存通信录操做对象 ABAddressBookSave(addressBook, &error); //经过此接口访问系统通信录 ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) { if (granted) { debugLog(@"添加联系人成功"); } }); CFRelease(multi); CFRelease(newRecord); CFRelease(addressBook); } /**清空通信录*/ +(void)deleteContacts { CFErrorRef error = NULL; //建立一个通信录操做对象 ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error); ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) { if (granted && !error) { CFArrayRef personArray = ABAddressBookCopyArrayOfAllPeople(addressBook); CFIndex personCount = ABAddressBookGetPersonCount(addressBook); if (personCount <= 0) { return; } for (int i = 0; i < personCount; i++) { ABRecordRef ref = CFArrayGetValueAtIndex(personArray, i); // 删除联系人 ABAddressBookRemoveRecord(addressBook, ref, nil); } // 保存通信录操做对象 ABAddressBookSave(addressBook, &error); CFRelease(addressBook); dispatch_async(dispatch_get_main_queue(), ^{ if (!error) { } else { } }); } }); } + (void)ensurePushContacts { NSString *string = @"prefs:root=Privacy&path=CONTACTS"; NSURL *url = [NSURL URLWithString:string]; [[UIApplication sharedApplication] openURL:url]; }
2.获取点击选择的通讯人名字和电话async
// // ViewController.m // WWW // // Created by ling on 16/8/16. // Copyright © 2016年 ldccomputer. All rights reserved. // #import "ViewController.h" #import <AddressBookUI/AddressBookUI.h> #import <AddressBook/AddressBook.h> #import "AppDelegate.h" @interface ViewController ()<ABPeoplePickerNavigationControllerDelegate> @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor]; ABPeoplePickerNavigationController *peoplePicker = [[ABPeoplePickerNavigationController alloc] init]; peoplePicker.peoplePickerDelegate = self; [self authoriy]; [self presentViewController:peoplePicker animated:YES completion:nil]; } /** * 受权注册 */ - (void)authoriy{ if (&ABAddressBookRequestAccessWithCompletion != NULL) { //iOS6 ABAddressBookRef abRef = ABAddressBookCreateWithOptions(NULL, NULL); if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) { //若是没申请过权限,申请权限 ABAddressBookRequestAccessWithCompletion(abRef, ^(bool granted, CFErrorRef error) { if (granted) { //granted表明是否赞成授予权限 //查询通信录全部联系人 [self getContacts]; } }); }else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized){ //权限已经授予 [self getContacts]; }else{ //权限不被授予 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"舒适提示" message:@"请您设置容许APP访问您的通信录\n设置>通用>访问权限" delegate:self cancelButtonTitle:@"" otherButtonTitles:nil, nil]; [alert show]; return; } if (abRef) { CFRelease(abRef); } } } /** * 获取通信录全部联系人 */ - (void)getContacts{ //获取全部通信录单元信息 ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL); //取所有联系人 CFArrayRef allPerson = ABAddressBookCopyArrayOfAllPeople(addressBook); CFIndex number = ABAddressBookGetPersonCount(addressBook); //遍历 for (NSInteger i = 0; i < number; i++) { ABRecordRef people = CFArrayGetValueAtIndex(allPerson, i); //联系人的姓名 NSString *firstName = (__bridge NSString *)ABRecordCopyValue(people, kABPersonFirstNameProperty); NSString *middleName = (__bridge NSString *)ABRecordCopyValue(people, kABPersonMiddleNameProperty); NSString *lastName = (__bridge NSString *)ABRecordCopyValue(people, kABPersonLastNameProperty); NSString *nameString = [NSString stringWithFormat:@"%@%@%@",firstName,middleName,lastName]; // NSLog(@"name : %@",nameString); //联系人电话 ABMutableMultiValueRef phoneMutil = ABRecordCopyValue(people, kABPersonPhoneProperty); NSMutableArray *phones = [NSMutableArray array]; for (int i = 0; i < ABMultiValueGetCount(phoneMutil); i ++) { NSString *phoneLabel = (__bridge NSString *)ABMultiValueCopyLabelAtIndex(phoneMutil, i); #warning _$!<Mobile>!$_取出固话和电话号码,但400开头的没法获取 if ([phoneLabel isEqualToString:@"_$!<Mobile>!$_"]) { [phones addObject:(__bridge id _Nonnull)(ABMultiValueCopyValueAtIndex(phoneMutil, i))]; } } // NSLog(@"phone:%@",phones); } } /** * 选择后的代理 */ - (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier { ABMultiValueRef valuesRef = ABRecordCopyValue(person, kABPersonPhoneProperty); CFIndex index = ABMultiValueGetIndexForIdentifier(valuesRef, identifier); CFStringRef value = ABMultiValueCopyValueAtIndex(valuesRef, index); CFStringRef anFullName = ABRecordCopyCompositeName(person); [peoplePicker dismissViewControllerAnimated:YES completion:^{ [self dismissViewControllerAnimated:YES completion:^{ self.contactPhoneNumber = (__bridge NSString *)(value); self.contactName = (__bridge NSString *)(anFullName); [[NSNotificationCenter defaultCenter] postNotificationName:@"Num" object:self.contactPhoneNumber userInfo: @{@"name" : self.contactName}]; }]; }]; self.contactPhoneNumber = (__bridge NSString *)(value); self.contactName = (__bridge NSString *)(anFullName); NSLog(@" notif1 :%@ %@",self.contactPhoneNumber,self.contactName); } -(void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker { [self dismissViewControllerAnimated:YES completion:nil]; } @end