美文网首页
iOS获取联系人信息

iOS获取联系人信息

作者: MI移动 | 来源:发表于2021-05-31 11:45 被阅读0次

    iOS 9.0之前

    - (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;
        }
    }
    

    iOS 9.0之后(两种方式)

    一:通过代码就可以获取所有通讯录信息(需要用户授权)

    image.png
    获取用户授权
    申请使用通讯录,在无权限时提示用户打开权限
    导入 #import <Contacts/Contacts.h>
    - (IBAction)getMailListAction:(id)sender {
        
        CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
        if (status == CNAuthorizationStatusNotDetermined) {
            CNContactStore *store = [[CNContactStore alloc] init];
            [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError*  _Nullable error) {
                if (error) {
                    //无权限
                    [self showAlertViewAboutNotAuthorAccessContact];
                } else {
                    //有权限
                    [self openContact];
                }
            }];
        } else if(status == CNAuthorizationStatusRestricted) {
            //无权限
            [self showAlertViewAboutNotAuthorAccessContact];
        } else if (status == CNAuthorizationStatusDenied) {
            //无权限
            [self showAlertViewAboutNotAuthorAccessContact];
        } else if (status == CNAuthorizationStatusAuthorized) {
            //有权限
            [self openContact];
        }
        
    }
    
    - (void)showAlertViewAboutNotAuthorAccessContact{
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"请授权通讯录权限" message:@"请在iPhone的\"设置-隐私-通讯录\"选项中,允许花解解访问你的通讯录" preferredStyle: UIAlertControllerStyleAlert];
        UIAlertAction *OKAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:OKAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }
    
    // 获取所有联系人信息
    - (void)openContact{
        
        NSArray *keysToFetch = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey];
        CNContactFetchRequest *fetchRequest = [[CNContactFetchRequest alloc] initWithKeysToFetch:keysToFetch];
        CNContactStore *contactStore = [[CNContactStore alloc] init];
        
        [contactStore enumerateContactsWithFetchRequest:fetchRequest error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
            
            NSString * firstName = contact.familyName;
            NSString * lastName = contact.givenName;
            
            //电话
            NSArray * phoneNums = contact.phoneNumbers;
            CNLabeledValue *labelValue = phoneNums.firstObject;
            NSString *phoneValue = [labelValue.value stringValue];
            
            NSLog(@"姓名:%@%@ 电话:%@", firstName, lastName, phoneValue);
            
        }];
    }
    

    二:打开通讯录选择界面,单选或者多选联系人,以获取信息(无需用户授权)

    1. 打开通讯录界面
    #import <ContactsUI/ContactsUI.h>
    #import <Contacts/Contacts.h>
    
    @interface ViewController () <CNContactPickerDelegate>
    
    @end
    
    @implementation ViewController {
        CNContactPickerViewController * _peoplePickVC;
    }
    
    - (void)viewDidLoad {
        [super viewDidLoad];
    }
    
    - (IBAction)openMailListAction:(id)sender {
        _peoplePickVC = [[CNContactPickerViewController alloc] init];
        _peoplePickVC.delegate = self;
        [self showViewController:_peoplePickVC sender:nil];
    }
    

    注意 CNContactPickerViewController 对象需要定义为全局变量。

    1. 获取单个联系人信息
    // 获取指定联系人 里面只log了第一个电话号码
    - (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact {
    
        //姓名
        NSString * firstName = contact.familyName;
        NSString * lastName = contact.givenName;
    
        //电话
        NSArray * phoneNums = contact.phoneNumbers;
        CNLabeledValue *labelValue = phoneNums.firstObject;
        NSString *phoneValue = [labelValue.value stringValue];
    
        NSLog(@"姓名:%@%@ 电话:%@", firstName, lastName, phoneValue);
    }
    
    1. 获取单个联系人指定电话
    // 获取指定电话
    - (void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperty:(CNContactProperty *)contactProperty {
    
        //姓名
        NSString * firstName = contactProperty.contact.familyName;
        NSString * lastName = contactProperty.contact.givenName;
    
        //电话
        NSString * phoneNum = [contactProperty.value stringValue];
    
        NSLog(@"姓名:%@%@ 电话:%@", firstName, lastName, phoneNum);
    }
    
    1. 获取多个联系人信息
    //获取多个联系人 里面只log了每个联系人第一个电话号码
    - (void)contactPicker:(CNContactPickerViewController *)picker didSelectContacts:(NSArray<CNContact *> *)contacts {
    
        //遍历
        for (CNContact * contact in contacts) {
    
            //姓名
            NSString * firstName = contact.familyName;
            NSString * lastName = contact.givenName;
    
            //电话
            NSArray * phoneNums = contact.phoneNumbers;
            CNLabeledValue *labelValue = phoneNums.firstObject;
            NSString *phoneValue = [labelValue.value stringValue];
    
            NSLog(@"姓名:%@%@ 电话:%@", firstName, lastName, phoneValue);
    
        }
    }
    
    • 只可实现一个代理方法,同时实现多个代理方法只会生效一个,导致弹出的联系人选择页面不是你想要的效果。

    相关文章

      网友评论

          本文标题:iOS获取联系人信息

          本文链接:https://www.haomeiwen.com/subject/pdzvsltx.html