二、获取手机通讯录

最近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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 180,428评论 25 708
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 16,742评论 4 61
  • 通讯录简介 通讯录使用场景: 电商类的 App,设置收货人电话号码。 即时通讯类 App,添加手机联系人好友。 通...
    LeeJay阅读 25,216评论 43 107
  • 从何说起呢? 最近秋田酱喜欢上了一位傲娇的neko桑。 额,或者说是,秋田酱单方面地疯狂地爱上了一个她很喜欢很喜欢...
    Joe_Wang阅读 354评论 0 0
  • 落伍阅读 448评论 0 0

友情链接更多精彩内容