美文网首页
二、获取手机通讯录

二、获取手机通讯录

作者: LeeLeCoder | 来源:发表于2017-03-30 19:54 被阅读0次

    最近APP中需要做获取通讯录中的手机联系人, 根据手机号码匹配app中的联系人, 判断在app中是否已经是自己好友,如果不是好友可以添加为好友。

    1. 需要导入的框架

    #import <AddressBook/AddressBook.h>
    #import <AddressBookUI/AddressBookUI.h>
    

    2. 需要遵守的协议

    ABPeoplePickerNavigationControllerDelegate
    

    3. 创建联系人model

    #import <Foundation/Foundation.h>
    
    @interface ContactModel : NSObject
    
    @property (nonatomic, copy) NSString *name; // 解析后 真正的name
    
    @property (nonatomic, copy) NSString *firstName;
    @property (nonatomic, copy) NSString *lastName;
    @property (nonatomic, copy) NSString *midName;
    @property (nonatomic, copy) NSString *prefix;
    @property (nonatomic, copy) NSString *suffix;
    @property (nonatomic, copy) NSString *nickName;
    @property (nonatomic, copy) NSString *firstNamePhonetic; // firstName拼音音标
    @property (nonatomic, copy) NSString *lastNamePhonetic; //
    @property (nonatomic, copy) NSString *midNamePhonetic; //
    @property (nonatomic, copy) NSString *organiztion; // 公司
    @property (nonatomic, copy) NSString *jobTitle; // 工作
    @property (nonatomic, copy) NSString *department; // 部门
    @property (nonatomic, copy) NSString *birthday; // 生日
    @property (nonatomic, copy) NSString *note; // 备忘
    @property (nonatomic, copy) NSString *creationDate; // 第一次添加该记录的时间
    @property (nonatomic, copy) NSString *modificationDate; // 最后一次修改改天记录的时间
    @property (nonatomic, strong) NSMutableArray  *emailCount; // email
    @property (nonatomic, strong) NSMutableArray  *address; // 地址
    @property (nonatomic, strong) NSMutableArray  *dates; // dates多值
    @property (nonatomic, copy) NSString *kind; // kind多值
    @property (nonatomic, strong) NSMutableArray  *instantMessage; // IM
    @property (nonatomic, strong) NSMutableArray  *phones; // 电话多值
    @property (nonatomic, strong) NSMutableArray  *url; // URL多值
    @property (nonatomic, strong) NSData   *headImage; // 照片
    
    @end
    

    4. 获取手机通讯录中的联系人

    - (void)viewDidLoad {
        [super viewDidLoad];
        self.navigationItem.title = @"联系人";
        [self createLinkManTableView];
        [self loadPresion];
    }
    
    - (void)createLinkManTableView{
        self.linkManTableView = [[UITableView alloc]initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
        self.linkManTableView.delegate = self;
        self.linkManTableView.dataSource = self;
        [self.view addSubview:self.linkManTableView];
        [self.linkManTableView registerClass:[XYCustomCell class] forCellReuseIdentifier:XYCell];
    }
    
    // 查看是否已经获取通讯录权限
    - (void)loadPresion{
        ABAddressBookRef addressBookref = ABAddressBookCreateWithOptions(NULL, NULL);
        if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
            ABAddressBookRequestAccessWithCompletion(addressBookref, ^(bool granted, CFErrorRef error) {
                CFErrorRef *error1 = NULL;
                ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error1);
                [self copyAddressBook:addressBook];
            });
        }else if(ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized){
            CFErrorRef *error1 = NULL;
            ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error1);
            [self copyAddressBook:addressBook];
    
        }else{
            UIAlertView *alert  = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有获取通讯录权限" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
            alert.delegate = self;
            [alert show];
        }
    }
    
    - (void)copyAddressBook:(ABAddressBookRef)addressBook{
        //获取联系人个数
        CFIndex numberOfPeoples = ABAddressBookGetPersonCount(addressBook);
        CFArrayRef peoples = ABAddressBookCopyArrayOfAllPeople(addressBook);
        NSLog(@"有%ld个联系人", numberOfPeoples);
        //循环获取联系人
        for (int i = 0; i < numberOfPeoples; i++) {
            ABRecordRef person = CFArrayGetValueAtIndex(peoples, i);
            ContactModel *linkMan = [[ContactModel alloc] init];
            linkMan.firstName = (__bridge NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
            linkMan.lastName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));
            linkMan.nickName = (__bridge NSString*)ABRecordCopyValue(person, kABPersonNicknameProperty);
            linkMan.organiztion = (__bridge NSString*)ABRecordCopyValue(person, kABPersonOrganizationProperty);
            linkMan.headImage = (__bridge NSData*)ABPersonCopyImageData(person);
    
    
            if (linkMan.firstName && linkMan.lastName) {
                linkMan.name = [NSString stringWithFormat:@"%@%@",linkMan.lastName, linkMan.firstName];
            }else if(!linkMan.firstName){
                linkMan.name = linkMan.lastName;
            }else{
                linkMan.name = linkMan.firstName;
            }
            if (!linkMan.name) {
                linkMan.name = linkMan.organiztion;
            }
            if (linkMan.nickName) {
                linkMan.name =[NSString stringWithFormat:@"%@", linkMan.nickName];
            }
    
            //读取电话多值
            NSMutableArray *phoneArray = [[NSMutableArray alloc] init];
            ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
            for (int k = 0; k<ABMultiValueGetCount(phone); k++)
            {
                //获取电话Label
                NSString * personPhoneLabel = (__bridge NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phone, k));
                //获取該Label下的电话值
                NSString * tempstr = (__bridge NSString*)ABMultiValueCopyValueAtIndex(phone, k);
                NSArray *array = [NSArray arrayWithObjects:personPhoneLabel, tempstr, nil];
                [phoneArray addObject:array];
            }
             linkMan.phones = phoneArray;
            [self.linkManArray addObject:linkMan];
        }
        NSDictionary *dict = [ICPinyinGroup group:self.linkManArray  key:@"name"];
    
        self.tableHeaderArray = [dict objectForKey:LEOPinyinGroupCharKey];
        self.sortedArrForArrays = [dict objectForKey:LEOPinyinGroupResultKey];
        [self performSelectorOnMainThread:@selector(reloadTable) withObject:nil waitUntilDone:YES];
    }
    
    - (void)reloadTable{
        [self.linkManTableView reloadData];
    
    }
    #pragma TableView代理方法
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
        return [self.sortedArrForArrays count];
    }
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
        return [[self.sortedArrForArrays objectAtIndex:section] count];
    }
    - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
    {
        return [self.tableHeaderArray objectAtIndex:section];
    }
    //侧边栏
    - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
        return self.tableHeaderArray;
    }
    
    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
        return 55;
    }
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
        XYCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:XYCell];
    
        if(self.sortedArrForArrays.count > indexPath.section){
            NSArray *array = [self.sortedArrForArrays objectAtIndex:indexPath.section];
            if (array.count > indexPath.row) {
                ContactModel *linkManModel = [array objectAtIndex:indexPath.row];
                cell.headImageView.image = [UIImage imageWithData:linkManModel.headImage];
                if (!linkManModel.headImage) {
                cell.headImageView.image = [UIImage imageNamed:@"headImage"];
                }
    
                cell.titleLabel.text = linkManModel.name;
                if (linkManModel.phones.count == 0) {
                    return cell;
                }
                NSString *numStr = @"电话";
                if (linkManModel.phones.count > 1){
                    numStr = @"电话一";
                }
                NSArray *array = [linkManModel.phones objectAtIndex:0];
                cell.summaryLabel.text = [NSString stringWithFormat:@"%@:%@", numStr, [array objectAtIndex:1]];
            }
        }
        return cell;
    }
    
    - (NSMutableArray *)linkManArray{
        if (_linkManArray == nil) {
            _linkManArray = [[NSMutableArray alloc] init];
        }
        return _linkManArray;
    }
    - (NSMutableArray *)tableHeaderArray{
        if (_tableHeaderArray == nil) {
            _tableHeaderArray = [[NSMutableArray alloc] init];
        }
        return _tableHeaderArray;
    }
    - (NSMutableArray *)sortedArrForArrays{
        if (_sortedArrForArrays == nil) {
            _sortedArrForArrays = [[NSMutableArray alloc] init];
        }
        return _sortedArrForArrays;
    }
    

    参考博客: http://www.jianshu.com/p/6acad14cf3c9

    相关文章

      网友评论

          本文标题:二、获取手机通讯录

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