iOS获取通讯录所有联系人信息
以下是2种方式:
第一种方法:
GetAddressBook.h
#import <Foundation/Foundation.h> @interface GetAddressBook : NSObject - (NSArray *)getAddressBookAction; @end
GetAddressBook.m
#import "GetAddressBook.h" #import "ContactAddressModel.h" #import "NSDate+TimeCategory.h" #import <AddressBook/AddressBook.h> @interface GetAddressBook () @property (nonatomic, strong) NSArray *arr; @end @implementation GetAddressBook - (NSArray *)getAddressBookAction { WEAKSELF weaktype.arr = nil; 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); }); weaktype.arr = contacts; } else { // 拒绝 NSLog(@"拒绝"); } } else { NSLog(@"错误!"); } }); return weaktype.arr; } else { // 非首次访问通讯录 NSArray *contacts = [self fetchContactWithAddressBook:addressBook]; dispatch_async(dispatch_get_main_queue(), ^{ // NSLog(@"contacts:%@", contacts); }); return contacts; } } - (NSMutableArray *)fetchContactWithAddressBook:(ABAddressBookRef)addressBook { if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) { // 有权限访问 NSMutableArray *contacts = [[NSMutableArray alloc] init]; // 获取联系人数组 NSArray *array = (__bridge NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook); for (int i = 0; i < array.count; i++) { // NSDictionary *dict = [[NSDictionary alloc] init]; // 获取联系人 ABRecordRef people = CFArrayGetValueAtIndex((__bridge ABRecordRef)array, i); // 获取联系人详细信息,如:姓名,电话,住址等信息 NSString *firstName = (__bridge NSString *)ABRecordCopyValue(people, kABPersonFirstNameProperty); NSString *lastName = (__bridge NSString *)ABRecordCopyValue(people, kABPersonLastNameProperty); // 判断姓名null NSString *displayName; if (lastName.length > 0 || firstName.length > 0) { displayName = [NSString stringWithFormat:@"%@%@", lastName, firstName]; } else { displayName = @""; } ABMutableMultiValueRef phoneRef = ABRecordCopyValue(people, kABPersonPhoneProperty); NSArray *phoneList = ((__bridge NSArray *)ABMultiValueCopyArrayOfAllValues(phoneRef)); for (int j = 0; j < phoneList.count; j++) { NSMutableDictionary *addressBookMDic = [NSMutableDictionary dictionary]; [addressBookMDic setValue:displayName forKey:@"name"]; [addressBookMDic setValue:phoneList[j] forKey:@"mobile"]; [contacts addObject:addressBookMDic]; } } return contacts; } else { // 无权限访问 // 提示授权 // UIAlertView * alart = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"请您设置允许APP访问您的通讯录\n设置-隐私-通讯录" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil]; // [alart show]; return nil; } } @end
第二种方法:
GetContactVC.h
#import <UIKit/UIKit.h> @interface GetContactVC : UIViewController @end
GetContactVC.m
#import "GetContactVC.h" #import <AddressBook/AddressBook.h> #import <ContactsUI/ContactsUI.h> @interface GetContactVC () { UITableView *infoTable; NSMutableArray *dataArray; NSMutableDictionary *dataSectionData; NSMutableArray *allKeysArray; NSMutableArray *sortkeysArray; /** * 创建CNContactStore对象,用与获取和保存通讯录信息 */ CNContactStore *contactStore; } @end @implementation GetContactVC - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor yellowColor]; if (@available(iOS 9.0, *)) { [self fetchAddressBookOnIOS9AndLater]; } else { [self fetchAddressBookBeforeIOS9]; } } - (void)fetchAddressBookOnIOS9AndLater{ //创建CNContactStore对象 CNContactStore *contactStore = [[CNContactStore alloc] init]; //首次访问需用户授权 if ([CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts] == CNAuthorizationStatusNotDetermined) {//首次访问通讯录 [contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) { if (!error){ if (granted) {//允许 NSLog(@"已授权访问通讯录"); NSArray *contacts = [self fetchContactWithContactStore:contactStore];//访问通讯录 dispatch_async(dispatch_get_main_queue(), ^{ //----------------主线程 更新 UI----------------- NSLog(@"contacts:%@", contacts); }); }else{//拒绝 NSLog(@"拒绝访问通讯录"); } }else{ NSLog(@"发生错误!"); } }]; }else{ //非首次访问通讯录 NSArray *contacts = [self fetchContactWithContactStore:contactStore];//访问通讯录 dispatch_async(dispatch_get_main_queue(), ^{ //----------------主线程 更新 UI----------------- NSLog(@"contacts:%@", contacts); }); } } - (NSMutableArray *)fetchContactWithContactStore:(CNContactStore *)contactStore{ //判断访问权限 if ([CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts] == CNAuthorizationStatusAuthorized) {//有权限访问 NSError *error = nil; //创建数组,必须遵守CNKeyDescriptor协议,放入相应的字符串常量来获取对应的联系人信息 NSArray <id<CNKeyDescriptor>> *keysToFetch = @[CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey]; //获取通讯录数组 NSArray<CNContact*> *arr = [contactStore unifiedContactsMatchingPredicate:nil keysToFetch:keysToFetch error:&error]; if (!error) { NSMutableArray *contacts = [NSMutableArray array]; for (int i = 0; i < arr.count; i++) { CNContact *contact = arr[i]; NSString *givenName = contact.givenName; NSString *familyName = contact.familyName; NSString *phoneNumber = @"NULL"; if ((CNPhoneNumber *)(contact.phoneNumbers.lastObject.value)) { phoneNumber = ((CNPhoneNumber *)(contact.phoneNumbers.lastObject.value)).stringValue; } [contacts addObject:@{@"name": [givenName stringByAppendingString:familyName], @"phoneNumber": phoneNumber}]; } return contacts; }else { return nil; } }else{//无权限访问 NSLog(@"无权限访问通讯录"); return nil; } } - (void)fetchAddressBookBeforeIOS9{ ABAddressBookRef addressBook = ABAddressBookCreate(); //首次访问需用户授权 if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {//首次访问通讯录 ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) { if (!error) { if (granted) {//允许 NSLog(@"已授权访问通讯录"); NSArray *contacts = [self fetchContactWithAddressBook:addressBook]; dispatch_async(dispatch_get_main_queue(), ^{ //----------------主线程 更新 UI----------------- NSLog(@"contacts:%@", contacts); }); }else{//拒绝 NSLog(@"拒绝访问通讯录"); } }else{ NSLog(@"发生错误!"); } }); }else{//非首次访问通讯录 NSArray *contacts = [self fetchContactWithAddressBook:addressBook]; dispatch_async(dispatch_get_main_queue(), ^{ //----------------主线程 更新 UI----------------- 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; } } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. }