抓取通讯录

#import 
#import 
#import 
#import 
#import 

添加代理方法


iOS9.0以后用的方法

pragma mark - 点击某个联系人的某个属性(property)时触发并返回该联系人属性(contactProperty)。

//只实现该方法时,可以进入到联系人详情页面(如果predicateForSelectionOfProperty属性没被设置或符合筛选条件,如不符合会触发默认操作,即打电话,发邮件等)。

- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperty:(CNContactProperty *)contactProperty  API_AVAILABLE(ios(9.0)){
    NSLog(@"%@",contactProperty);
    CNContact *contact = contactProperty.contact;
    NSLog(@"givenName: %@, familyName: %@", contact.givenName, contact.familyName);
    //    self.nameTextView.text = [NSString stringWithFormat:@"%@%@",contact.familyName,contact.givenName];
    if (![contactProperty.value isKindOfClass:[CNPhoneNumber class]]) {
        //        [[HNPublicTool shareInstance] showHudErrorMessage:@"请选择11位手机号"];
        return;
    }
    CNPhoneNumber *phoneNumber = contactProperty.value;
    NSString *phoneStr = [self RemoveSpecialCharacters:phoneNumber.stringValue];
    NSLog(@"号码:%@",phoneStr);
    if ([self valiMobile:phoneStr]) {
        BasicInfoAndContactsModel *model = self.dataMutArray[self.indexPath.row];
        model.subTitle = phoneStr;
        [self.tableView reloadData];
    }else{
        [Utils showToast:@"手机号码不正确,请重新选择."];
    }
    
}

//请求通讯录权限

pragma mark 请求通讯录权限

- (void)requestContactAuthorAfterSystemVersion9{
    
    if (@available(iOS 9.0, *)) {
        CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
        if (status == CNAuthorizationStatusNotDetermined) {
            CNContactStore *store = [[CNContactStore alloc] init];
            [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError*  _Nullable error) {
                if (error) {
                    NSLog(@"授权失败");
                }else {
                    NSLog(@"成功授权");
                    CNContactPickerViewController *contactPickerViewController = [[CNContactPickerViewController alloc] init];
                    contactPickerViewController.delegate = self;
                    contactPickerViewController.displayedPropertyKeys = @[CNContactPhoneNumbersKey];
                    [self presentViewController:contactPickerViewController animated:YES completion:nil];
                    
                    [self openContact];
                }
            }];
        }
        else if(status == CNAuthorizationStatusRestricted)
        {
            NSLog(@"用户拒绝");
            [self showAlertViewAboutNotAuthorAccessContact];
        }
        else if (status == CNAuthorizationStatusDenied)
        {
            NSLog(@"用户拒绝");
            [self showAlertViewAboutNotAuthorAccessContact];
        }
        else if (status == CNAuthorizationStatusAuthorized)//已经授权
        {
            //有通讯录权限-- 进行下一步操作
            CNContactPickerViewController *contactPickerViewController = [[CNContactPickerViewController alloc] init];
            contactPickerViewController.delegate = self;
            contactPickerViewController.displayedPropertyKeys = @[CNContactPhoneNumbersKey];
            [self presentViewController:contactPickerViewController animated:YES completion:nil];
            
            [self openContact];
        }
        
    } else {
        // Fallback on earlier versions
        [self requestAuthorizationAddressBook];
    }
    
}

//有通讯录权限-- 进行下一步操作

- (void)openContact{
    [self.phoneBookMutArray removeAllObjects];
    // 获取指定的字段,并不是要获取所有字段,需要指定具体的字段
    if (@available(iOS 9.0, *)) {
        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) {
            NSLog(@"-------------------------------------------------------");
            
            NSString *givenName = contact.givenName;
            NSString *familyName = contact.familyName;
            NSLog(@"givenName=%@, familyName=%@", givenName, familyName);
            //拼接姓名
            NSString *nameStr = [NSString stringWithFormat:@"%@%@",[Utils strIsNil:contact.familyName] ? @"" : contact.familyName,[Utils strIsNil:contact.givenName] ? @"" : contact.givenName];
            
            NSArray *phoneNumbers = contact.phoneNumbers;
            NSMutableArray *phoneArray = [NSMutableArray array];
            for (CNLabeledValue *labelValue in phoneNumbers) {
                //遍历一个人名下的多个电话号码
                //            NSString *label = labelValue.label;
                //            NSString *    phoneNumber = labelValue.value;
                CNPhoneNumber *phoneNumber = labelValue.value;
                
                NSString * string = [self RemoveSpecialCharacters:phoneNumber.stringValue] ;
                [phoneArray addObject:string];
                NSLog(@"姓名=%@, 电话号码是=%@", nameStr, string);
            }
            NSDictionary *dict = @{
                                   @"name" : nameStr,
                                   @"phones" : phoneArray
                                   };
            [self.phoneBookMutArray addObject:dict];
            //    *stop = YES; // 停止循环,相当于break;
            
        }];
    } else {
        // Fallback on earlier versions
    }
    
    
}

//提示没有通讯录权限

- (void)showAlertViewAboutNotAuthorAccessContact{
    
    UIAlertController *alertController = [UIAlertController
                                          alertControllerWithTitle:@"请授权通讯录权限"
                                          message:@"请在iPhone的\"设置-隐私-通讯录\"选项中,允许APP访问你的通讯录"
                                          preferredStyle: UIAlertControllerStyleAlert];
    
    UIAlertAction *OKAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:OKAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

pragma mark - 系统8.0通讯录方法

- (void)requestAuthorizationAddressBook {//系统8.0请求通讯录权限
    __weak typeof(self)weakSelf = self;
    ABAddressBookRef bookref = ABAddressBookCreateWithOptions(NULL, NULL);
    ABAuthorizationStatus status = ABAddressBookGetAuthorizationStatus();
    /*kABAuthorizationStatusNotDetermined = 0,    // 未进行授权选择
     kABAuthorizationStatusRestricted,           // 未授权,且用户无法更新,如家长控制情况下
     kABAuthorizationStatusDenied,               // 用户拒绝App使用
     kABAuthorizationStatusAuthorized            // 已授权,可使用*/
    if (status == kABAuthorizationStatusNotDetermined) {
        ABAddressBookRequestAccessWithCompletion(bookref, ^(bool granted, CFErrorRef error) {
            if (error) {
                NSLog(@"授权错误");
            }
            if (granted) {
                NSLog(@"授权chengg");
                ABPeoplePickerNavigationController *peosonVC = [[ABPeoplePickerNavigationController alloc] init];
                peosonVC.peoplePickerDelegate = weakSelf;
                peosonVC.displayedProperties = @[[NSNumber numberWithInt:kABPersonPhoneProperty]];
                [weakSelf presentViewController:peosonVC animated:YES completion:nil];
                [self getAllPeoplePhoneNumber];
            }
        });
    }
    if (status == kABAuthorizationStatusAuthorized) {
        ABPeoplePickerNavigationController *peosonVC = [[ABPeoplePickerNavigationController alloc] init];
        peosonVC.peoplePickerDelegate = weakSelf;
        peosonVC.displayedProperties = @[[NSNumber numberWithInt:kABPersonPhoneProperty]];
        [weakSelf presentViewController:peosonVC animated:YES completion:nil];
        [self getAllPeoplePhoneNumber];
    }else
    {
//        @"您未开启通讯录权限,请前往设置中心开启"];
        UIAlertView * alart = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"请您设置允许APP访问您的通讯录\n设置-隐私-通讯录" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alart show];
    }
    
}

pragma mark - ios8走这个 选中联系人的某个属性的时候调用

- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
{
    // 获取该联系人多重属性--电话号
    ABMutableMultiValueRef phoneMulti = ABRecordCopyValue(person, kABPersonPhoneProperty);
    
    // 获取该联系人的名字,简单属性,只需ABRecordCopyValue取一次值
    ABMutableMultiValueRef firstName = ABRecordCopyValue(person, kABPersonFirstNameProperty);
    NSString *firstname = (__bridge NSString *)(firstName);
    ABMutableMultiValueRef lastName = ABRecordCopyValue(person, kABPersonLastNameProperty);
    NSString *lastname = (__bridge NSString *)(lastName);
    // 获取点击的联系人的电话
    NSLog(@"联系人名字 : %@%@",lastname,firstname);
    
    // 点击某个联系人电话后dismiss联系人控制器,并回调点击的数据
    [self dismissViewControllerAnimated:YES completion:^{
        // 从多重属性——电话号中取值,参数2是取点击的索引
        NSString *aPhone =  (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(phoneMulti, ABMultiValueGetIndexForIdentifier(phoneMulti,identifier)) ;
        // 去掉电话号中特殊符号
        aPhone = [self RemoveSpecialCharacters:aPhone];
        NSLog(@"去掉特殊符号:%@",aPhone);
        if ([self valiMobile:aPhone]) {
            BasicInfoAndContactsModel *model = self.dataMutArray[self.indexPath.row];
            model.subTitle = aPhone;
            [self.tableView reloadData];
        }else{
            [Utils showToast:@"手机号码不正确,请重新选择."];
        }
    }];
}

//抓取所有联系人

- (void)getAllPeoplePhoneNumber{
    [self.phoneBookMutArray removeAllObjects];
    // 2. 获取所有联系人
    ABAddressBookRef addressBookRef = ABAddressBookCreate();
    CFArrayRef arrayRef = ABAddressBookCopyArrayOfAllPeople(addressBookRef);
    long count = CFArrayGetCount(arrayRef);
    for (int i = 0; i < count; i++) {
        //获取联系人对象的引用
        ABRecordRef people = CFArrayGetValueAtIndex(arrayRef, i);
        
        //获取当前联系人名字
        NSString *firstName=(__bridge NSString *)(ABRecordCopyValue(people, kABPersonFirstNameProperty));
        
        //获取当前联系人姓氏
        NSString *lastName=(__bridge NSString *)(ABRecordCopyValue(people, kABPersonLastNameProperty));
        NSLog(@"--------------------------------------------------");
        NSLog(@"name=%@%@", ([Utils strIsNil:firstName] ? @"" : firstName), ([Utils strIsNil:lastName] ? @"" : lastName));
        NSString *name = [NSString stringWithFormat:@"%@%@", [Utils strIsNil:firstName] ? @"" : firstName, [Utils strIsNil:lastName] ? @"" : lastName];
        //获取当前联系人的电话 数组
        NSMutableArray *phoneArray = [[NSMutableArray alloc]init];
        ABMultiValueRef phones = ABRecordCopyValue(people, kABPersonPhoneProperty);
        for (NSInteger j=0; j

//去除电话号码中的特殊字符

- (NSString *)RemoveSpecialCharacters:(NSString *)str{
    NSString *string = str;
    string = [string stringByReplacingOccurrencesOfString:@"+86" withString:@""];
    NSCharacterSet *setToRemove = [[ NSCharacterSet characterSetWithCharactersInString:@"0123456789"]invertedSet];
    string = [[string componentsSeparatedByCharactersInSet:setToRemove]componentsJoinedByString:@""];
    return string;
}

pragma mark - 电话正则

- (BOOL)valiMobile:(NSString *)mobileNum
{
    if (mobileNum.length != 11)
    {
        return NO;
    }
    /**
     * 判断字符串是否符合手机号码格式
     * 移动号段: 134,135,136,137,138,139,147,150,151,152,157,158,159,170,178,182,183,184,187,188
     * 联通号段: 130,131,132,145,155,156,170,171,175,176,185,186
     * 电信号段: 133,149,153,170,173,177,180,181,189
     */
    NSString *telRegex = @"^((13[0-9])|(14[5,7,9])|(15[^4])|(18[0-9])|(17[0,1,3,5,6,7,8]))\\d{8}$";// "[1]"代表第1位为数字1,"[358]"代表第二位可以为3、5、8中的一个,"\\d{9}"代表后面是可以是0~9的数字,有9位。
    NSPredicate *regextestTelRegex = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", telRegex];
    if (([regextestTelRegex evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

你可能感兴趣的:(抓取通讯录)