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.获取点击选择的通信人名字和电话
//// ViewController.m// WWW//// Created by ling on 16/8/16.// Copyright © 2016年 ldccomputer. All rights reserved.//#import "ViewController.h"#import#import #import "AppDelegate.h"@interface ViewController () @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 _$! !$_取出固话和电话号码,但400开头的无法获取 if ([phoneLabel isEqualToString:@"_$! !$_"]) { [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