获取通讯录访问授权状态:
ABAuthorizationStatus type = ABAddressBookGetAuthorizationStatus();
/*
* kABAuthorizationStatusNotDetermined 用户还没有决定
* kABAuthorizationStatusRestricted 受限制
* kABAuthorizationStatusDenied 拒绝
* kABAuthorizationStatusAuthorized 许可
*/
在.h文件中申明:
///装载联系人记录的数组
@property (nonatomic, strong) NSArray *listContacts;
如果是第一次进入APP则会弹出提示框,询问用户是否允许APP访问通讯录。如果不是第一次进入APP,则根据之前的授权状态进入相应代码。
在.m文件中的viewDidLoad方法中加入:
///申请授权
CFErrorRef error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
if (granted) {//授权允许
[self filterContentForSearchText:@""]; //如果授权允许,则调用自定义的filterContentForSearchText:方法
} else {//授权拒绝
}
});
//释放Book
CFRelease(addressBook);
///查询通讯录联系人信息方法
- (void)filterContentForSearchText:(NSString *)searchText {
//如果没有授权,则退出
if (ABAddressBookGetAuthorizationStatus() != kABAuthorizationStatusAuthorized) {
return;
}
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
if ([searchText length] == 0) {
//查询所有
self.listContacts = CFBridgingRelease(ABAddressBookCopyArrayOfAllPeople(addressBook));
for (int i = 0; i < _listContacts.count; i++) {
ABRecordRef thisPerson = CFBridgingRetain([self.listContacts objectAtIndex:i]);
///读取名
NSString *firstName = CFBridgingRelease(ABRecordCopyValue(thisPerson, kABPersonFirstNameProperty));
firstName = firstName != nil?firstName:@"";
///读取姓
NSString *lastName = CFBridgingRelease(ABRecordCopyValue(thisPerson, kABPersonLastNameProperty));
lastName = lastName != nil?lastName:@"";
NSLog(@"第 %d 位联系人姓名为:%@ %@", i, firstName, lastName);
///读取多值属性--电话号码
ABRecordID personID = ABRecordGetRecordID(thisPerson);
ABRecordRef person = ABAddressBookGetPersonWithRecordID(addressBook, personID);
ABMultiValueRef phoneNumberProperty = ABRecordCopyValue(person, kABPersonPhoneProperty);
NSArray *phoneNumberArray = CFBridgingRelease(ABMultiValueCopyArrayOfAllValues(phoneNumberProperty));
for (int index = 0; index < phoneNumberArray.count; index++) {
NSString *phoneNumber = [phoneNumberArray objectAtIndex:index];
NSString *phoneNumberType = CFBridgingRelease(ABMultiValueCopyLabelAtIndex(phoneNumberProperty, index));
NSLog(@"他的 %@ 号码为:%@", phoneNumberType, phoneNumber);
}
CFRelease(phoneNumberProperty);
CFRelease(thisPerson);
}
} else {
//条件查询
}
}