iOS开发:通讯录联系人获取相关

首先你需要添加两个框架:

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

遵循协议:

ABPeoplePickerNavigationControllerDelegate

你还需要创建一个model类保存联系人对象

#import <Foundation/Foundation.h>

@interface XYLinkManModel : 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

然后是获取手机通讯录中的联系人

- (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);
        XYLinkManModel *linkMan = [[XYLinkManModel 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) {
            XYLinkManModel *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/605f49aa892c
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值