iOS获取通讯录 电话号码与姓名
Posted 一颗大牛的心
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS获取通讯录 电话号码与姓名相关的知识,希望对你有一定的参考价值。
// 还是导入
#import <AddressBook/AddressBook.h>
- (void)fetchAddressBookBeforeios9{
ABAddressBookRef addressBook = ABAddressBookCreate();
//用户授权
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {//首次访问通讯录
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
if (!error) {
if (granted) {//允许
NSArray *contacts = [self fetchContactWithAddressBook:addressBook];
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"contacts:%@", contacts);
});
}else{//拒绝
}
}else{
NSLog(@"错误!");
}
});
}else{//非首次访问通讯录
NSArray *contacts = [self fetchContactWithAddressBook:addressBook];
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"contacts:%@", contacts);
});
}
}
- (NSMutableArray *)fetchContactWithAddressBook:(ABAddressBookRef)addressBook{
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {////有权限访问
//获取联系人数组
NSArray *array = (__bridge NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
NSMutableArray *contacts = [NSMutableArray array];
for (int i = 0; i < array.count; i++) {
//获取联系人
ABRecordRef people = CFArrayGetValueAtIndex((__bridge ABRecordRef)array, i);
//获取联系人详细信息,如:姓名,电话,住址等信息
NSString *firstName = (__bridge NSString *)ABRecordCopyValue(people, kABPersonFirstNameProperty);
NSString *lastName = (__bridge NSString *)ABRecordCopyValue(people, kABPersonLastNameProperty);
ABMutableMultiValueRef *phoneNumRef = ABRecordCopyValue(people, kABPersonPhoneProperty);
NSString *phoneNumber = ((__bridge NSArray *)ABMultiValueCopyArrayOfAllValues(phoneNumRef)).lastObject;
[contacts addObject:@{@"name": [firstName stringByAppendingString:lastName], @"phoneNumber": phoneNumber}];
}
return contacts;
}else{//无权限访问
NSLog(@"无权限访问通讯录");
return nil;
}
}
以上是关于iOS获取通讯录 电话号码与姓名的主要内容,如果未能解决你的问题,请参考以下文章