获取通讯录的相关知识点,内容简单,希望对各位有所帮助,有何问题,欢迎留言(PS:虽然不一定回复您或者帮您解决,但好歹您老人家不要憋坏了)
/**
*获取通讯录信息
倒入头文件
在build phases 里面 导入 addressBook.framework 框架
*随着apple对用户隐私的越来越重视,IOS系统的权限设置也更加严格,在获取系统通讯录之前,我们必须获得用户的授权。权限申请代码示例如下:
*参考博客://http://www.open-open.com/code/view/1432302834146
*/
//授权 :如果不授权 是读不出通讯录信息的
- (void)getInfoOfAddressBookWithAuthorize
{
//这个变量用于记录授权是否成功,即用户是否允许我们访问通讯录
int __block tip=0;
//声明一个通讯簿的引用
ABAddressBookRef addBook =nil;
//因为在IOS6.0之后和之前的权限申请方式有所差别,这里做个判断
if ([[UIDevice currentDevice].systemVersion floatValue]>=6.0) {
//创建通讯簿的引用
addBook=ABAddressBookCreateWithOptions(NULL, NULL);
//创建一个出事信号量为0的信号
dispatch_semaphore_t sema=dispatch_semaphore_create(0);
//申请访问权限
ABAddressBookRequestAccessWithCompletion(addBook, ^(bool greanted, CFErrorRef
//greanted为YES是表示用户允许,否则为不允许
if
1;
}
//发送一次信号
dispatch_semaphore_signal(sema);
});
//等待信号触发
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
else{
//IOS6之前
ABAddressBookCreate();
}
if
//做一个友好的提示
UIAlertView * alart = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"请您设置允许APP访问您的通讯录\nSettings>General>Privacy" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
show];
return;
}
/*
几点注意:1、dispatch_semaphore_t三个相关的操作为
创建一个信号
发送一个信号
等待信号触发
创建一个信号,后面可以跟一个参数,表示信号量,当信号量正值时,dispatch_semaphore_wait后面的代码会被执行,否则程序将会一直等待在dispatch_semaphore_wait。 dispatch_semaphore_signal的作用是发送一个信号,会使信号量加1,相对的,dispatch_semaphore_wait执行后会使信号量减1.
、因为是否被授权是在ABAddressBookRequestAccessWithCompletion的block回调中获取的,所以我们需要在外面做一个线程等待
*/
// [self writeContractPerson:addBook];
self deleteInfo:addBook];
[self addressBookMessager:addBook];
CFRelease(addBook);
}
/*
* 四、重中之重-关于内存管理
上面的代码为了演示方便,创建的全部引用都没有释放,势必是造成内存泄露,在我们用ABAddressBookCreate()创建一个引用对象时,切记无论ARC还MRC,要用CFRelease()进行释放引用,例如上面的例子,我们需要加上这句代码
CFRelease(addBook);
如果你耐心的看到了这里,我想你一定明白了我为什么不在前边的代码里说明这个问题,因为在ARC项目普及的现在,这的确是重中之重。
*/
// 获取通讯录信息
- (void)addressBookMessager:(ABAddressBookRef
{
//随着apple对用户隐私的越来越重视,IOS系统的权限设置也更加严格,在获取系统通讯录之前,我们必须获得用户的授权。权限申请代码示例如下:
NSString *allName = nil;
//获取所有联系人的数组
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));
//获取当前联系人姓氏
NSString*lastName=(__bridge NSString *)(ABRecordCopyValue(people, kABPersonLastNameProperty));
//获取当前联系人中间名
NSString*middleName=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonMiddleNameProperty));
//获取当前联系人的名字前缀
NSString*prefix=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonPrefixProperty));
//获取当前联系人的名字后缀
NSString*suffix=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonSuffixProperty));
//获取当前联系人的昵称
NSString*nickName=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonNicknameProperty));
//获取当前联系人的名字拼音
NSString*firstNamePhoneic=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonFirstNamePhoneticProperty));
//获取当前联系人的姓氏拼音
NSString*lastNamePhoneic=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonLastNamePhoneticProperty));
//获取当前联系人的中间名拼音
NSString*middleNamePhoneic=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonMiddleNamePhoneticProperty));
//获取当前联系人的公司
NSString*organization=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonOrganizationProperty));
//获取当前联系人的职位
NSString*job=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonJobTitleProperty));
//获取当前联系人的部门
NSString*department=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonDepartmentProperty));
//获取当前联系人的生日
NSDate*birthday=(__bridge NSDate*)(ABRecordCopyValue(people, kABPersonBirthdayProperty));
NSMutableArray * emailArr = [[NSMutableArray alloc]init];
//获取当前联系人的邮箱 注意是数组
ABMultiValueRef emails= ABRecordCopyValue(people, kABPersonEmailProperty);
for (NSInteger j=0; j<ABMultiValueGetCount(emails); j++) {
addObject:(__bridge NSString *)(ABMultiValueCopyValueAtIndex(emails, j))];
}
//获取当前联系人的备注
NSString*notes=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonNoteProperty));
//获取当前联系人的电话 数组
NSMutableArray * phoneArr = [[NSMutableArray alloc]init];
ABMultiValueRef phones= ABRecordCopyValue(people, kABPersonPhoneProperty);
for (NSInteger j=0; j<ABMultiValueGetCount(phones); j++) {
addObject:(__bridge NSString *)(ABMultiValueCopyValueAtIndex(phones, j))];
}
/*
*对我需要的数据进行处理,这个自己去加以判断选择
*/
if (firstName == nil && middleName == nil && lastName == nil) {
firstObject];
}else {//如果没有名字的时候,在通讯录里面用电话号码去显示
if (firstName == nil) {
@"";
}
if (lastName == nil) {
@"";
}
if (middleName == nil) {
@"";
}
NSString stringWithFormat:@"%@%@%@",firstName,middleName,lastName];
}
self.dataList addObject:allName];
//获取创建当前联系人的时间 注意是NSDate
NSDate*creatTime=(__bridge NSDate*)(ABRecordCopyValue(people, kABPersonCreationDateProperty));
//获取最近修改当前联系人的时间
NSDate*alterTime=(__bridge NSDate*)(ABRecordCopyValue(people, kABPersonModificationDateProperty));
//获取地址
ABMultiValueRef address = ABRecordCopyValue(people, kABPersonAddressProperty);
for (int j=0; j<ABMultiValueGetCount(address); j++) {
//地址类型
NSString * type = (__bridge NSString *)(ABMultiValueCopyLabelAtIndex(address, j));
NSDictionary * temDic = (__bridge NSDictionary *)(ABMultiValueCopyValueAtIndex(address, j));
//地址字符串,可以按需求格式化
NSString * adress = [NSString stringWithFormat:@"国家:%@\n省:%@\n市:%@\n街道:%@\n邮编:%@",[temDic valueForKey:(NSString*)kABPersonAddressCountryKey],[temDic valueForKey:(NSString*)kABPersonAddressStateKey],[temDic valueForKey:(NSString*)kABPersonAddressCityKey],[temDic valueForKey:(NSString*)kABPersonAddressStreetKey],[temDic valueForKey:(NSString*)kABPersonAddressZIPKey]];
}
//获取当前联系人头像图片
NSData*userImage=(__bridge NSData*)(ABPersonCopyImageData(people));
//获取当前联系人纪念日
NSMutableArray * dateArr = [[NSMutableArray alloc]init];
ABMultiValueRef dates= ABRecordCopyValue(people, kABPersonDateProperty);
for (NSInteger j=0; j<ABMultiValueGetCount(dates); j++) {
//获取纪念日日期
NSDate * data =(__bridge NSDate*)(ABMultiValueCopyValueAtIndex(dates, j));
//获取纪念日名称
NSString * str =(__bridge NSString*)(ABMultiValueCopyLabelAtIndex(dates, j));
NSDictionary * temDic = [NSDictionary dictionaryWithObject:data forKey:str];
addObject:temDic];
}
}
/*
一定要释放内存
*/
CFRelease(allLinkPeople);
}
/**
*通讯录“写”的相关操作
*/
- (void)writeContractPerson:(ABAddressBookRef
//创建一个联系人引用
ABRecordRef person = ABPersonCreate();
NSString *firstName = @"哈1";
NSString *lastName = @"哈1";
NSData *birthday = nil;
// 电话号码数组
NSArray *phones = [NSArray arrayWithObjects:@"123",@"456",nil];
// 电话号码对应的名称
NSArray *labels = [NSArray arrayWithObjects:@"iphone",@"home",nil];
//这里的字段和上面的字段完全相同
// 设置名字属性
ABRecordSetValue(person, kABPersonFirstNameProperty,(__bridge CFStringRef)firstName, NULL);
// 设置姓氏属性
ABRecordSetValue(person, kABPersonLastNameProperty, (__bridge CFStringRef)lastName, NULL);
// 设置生日属性
ABRecordSetValue(person, kABPersonBirthdayProperty,(__bridge CFDateRef)birthday, NULL);
// 字典引用
ABMultiValueRef dic =ABMultiValueCreateMutable(kABMultiStringPropertyType);
// 添加电话号码与其对应的名称内容
for (int i = 0; i < [phones count]; i ++) {
ABMultiValueIdentifier obj = ABMultiValueAddValueAndLabel(dic,(__bridge CFStringRef)[phones objectAtIndex:i], (__bridge CFStringRef)[labels objectAtIndex:i], &obj);
}
// 设置phone属性
ABRecordSetValue(person, kABPersonPhoneProperty, dic, NULL);
// 将新建的联系人添加到通讯录中
ABAddressBookAddRecord(addBook, person, NULL);
// 保存通讯录数据
ABAddressBookSave(addBook, NULL);
CFRelease(person);
/*
、修改联系人
* 修改联系人的操作就是将获取和添加和在一起,先获取到相应的联系人引用,重设其属性字段即可。
*/
}
//删除联系人
- (void)deleteInfo:(ABAddressBookRef
//获取所有联系人
NSArray *array = (__bridge NSArray*)ABAddressBookCopyArrayOfAllPeople(addBook);
// 遍历所有的联系人
for (id obj in
ABRecordRef people = (__bridge ABRecordRef)obj;
NSString *firstName = (__bridge NSString*)ABRecordCopyValue(people, kABPersonFirstNameProperty);
NSString *lastName = (__bridge NSString*)ABRecordCopyValue(people, kABPersonLastNameProperty);
if ([firstName isEqualToString:@"哈"] &&[lastName isEqualToString:@"哈"]) {
ABAddressBookRemoveRecord(addBook, people,NULL);
}
}
// 保存修改的通讯录对象
ABAddressBookSave(addBook, NULL);
}
/*
场景一:直接选择一个联系人的电话号码《这种情景时弹出一个系统的VC,然后可以去选择通讯录一条信息,点击后有回弹出一个VC,您在选择后,可以获取相关联系人的信息,这时他会自动的反悔到上个页面,可以按返回按钮,回到最初您写的的页面》您可以在 协议方法里面做一些相关的处理
这里不需要先获取所有的联系人自己做联系人列表,直接使用系统自带的AddressBookUI/ABPeoplePickerNavigationController.h就好。
首先需要引入如下三个文件
#import <AddressBookUI/ABPeoplePickerNavigationController.h>
#import <AddressBook/ABPerson.h>
#import <AddressBookUI/ABPersonViewController.h>
然后初始化ABPeoplePickerNavigationController。
协议方法
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person NS_AVAILABLE_IOS(8_0);
// Called after a property has been selected by the user.
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier NS_AVAILABLE_IOS(8_0);
// Called after the user has pressed cancel.
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker;
// Deprecated, use predicateForSelectionOfPerson and/or -peoplePickerNavigationController:didSelectPerson: instead.
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person NS_DEPRECATED_IOS(2_0, 8_0);
// Deprecated, use predicateForSelectionOfProperty and/or -peoplePickerNavigationController:didSelectPerson:property:identifier: instead.
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier NS_DEPRECATED_IOS(2_0, 8_0);
*/
- (void)memorandum {
ABPeoplePickerNavigationController *nav = [[ABPeoplePickerNavigationController alloc] init];
nav.peoplePickerDelegate = self;
if([[UIDevice currentDevice].systemVersion floatValue] >= 8.0){
nav.predicateForSelectionOfPerson = [NSPredicate predicateWithValue:false];
}
[self presentViewController:nav animated:YES completion:nil];
/*
在iOS8之后,需要添加nav.predicateForSelectionOfPerson = [NSPredicate predicateWithValue:false];这一段代码,否则选择联系人之后会直接dismiss,不能进入详情选择电话。
*/
}
//取消选择
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController
{
[peoplePicker dismissViewControllerAnimated:YES completion:nil];
}
下
一个人被选中的人被用户选中。
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
long index = ABMultiValueGetIndexForIdentifier(phone,identifier);
NSString *phoneNO = (__bridge NSString *)ABMultiValueCopyValueAtIndex(phone, index);
if ([phoneNO hasPrefix:@"+"]) {
substringFromIndex:3];
}
phoneNO = [phoneNO stringByReplacingOccurrencesOfString:@"-" withString:@""];
NSLog(@"%@", phoneNO);
// if (phone && [ZXValidateHelper checkTel:phoneNO]) {
// phoneNum = phoneNO;
// [self.tableView reloadData];
// [peoplePicker dismissViewControllerAnimated:YES completion:nil];
// return;
// }
}
//一个人被选中的人被用户选中。
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person
{
ABPersonViewController *personViewController = [[ABPersonViewController alloc] init];
displayedPerson
pushViewController:personViewController animated:YES];
}
下
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
return YES;
}
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
{
ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
long index = ABMultiValueGetIndexForIdentifier(phone,identifier);
NSString *phoneNO = (__bridge NSString *)ABMultiValueCopyValueAtIndex(phone, index);
if ([phoneNO hasPrefix:@"+"]) {
substringFromIndex:3];
}
phoneNO = [phoneNO stringByReplacingOccurrencesOfString:@"-" withString:@""];
NSLog(@"%@", phoneNO);
// if (phone && [ZXValidateHelper checkTel:phoneNO]) {
// phoneNum = phoneNO;
// [self.tableView reloadData];
// [peoplePicker dismissViewControllerAnimated:YES completion:nil];
// return NO;
// }
return YES;
}