iOS通讯录的获取(AddressBook)

1.引入头文件

#import

2.启动项目时判断是否授权获取通讯录

2.1获取授权状态

ABAuthorizationStatusstatus =ABAddressBookGetAuthorizationStatus();

2.2判断授权状态,如果是未决定状态,才需要请求获取授权

if(status ==kABAuthorizationStatusNotDetermined)

2.3如果是未决定状态,则创建通信录对象

ABAddressBookRef  addressBook =ABAddressBookCreateWithOptions(NULL,NULL);

2.4请求授权

ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted,CFErrorRef error) {

if(granted) {

NSLog(@"授权成功");

}else{

NSLog(@"授权失败");

}

});

3.触发获取用户通信录的行为时,同样要先验证是否授权获取用户通信录,如果验证成功,则继续,否则提示用户权限验证失败,引导用户去设置页面打开权限

3.1创建通讯录对象

ABAddressBookRef addressBook =ABAddressBookCreateWithOptions(NULL,NULL);

3.2从通信录对象中,将所有的联系人拷贝出来

CFArrayRef  peopleArray =ABAddressBookCopyArrayOfAllPeople(addressBook);

3.3遍历所有的联系人

CFIndexpeopleCount =CFArrayGetCount(peopleArray);

for(CFIndexi =0; i < peopleCount; i++) {

//获取到联系人

ABRecordRefperson =CFArrayGetValueAtIndex(peopleArray, i);

// 获取姓名

NSString*lastname = (__bridge_transferNSString*)ABRecordCopyValue(person,kABPersonLastNameProperty);

NSString*firstName = (__bridge_transferNSString*)ABRecordCopyValue(person,kABPersonFirstNameProperty);

NSLog(@"%@ %@", lastname, firstName);

}

3.4释放不在使用的对象,都则造成内存泄露

CFRelease(peopleArray);

CFRelease(addressBook);

你可能感兴趣的:(iOS通讯录的获取(AddressBook))