二、获取手机通讯录

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,271评论 5 466
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,725评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,252评论 0 328
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,634评论 1 270
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,549评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,985评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,471评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,128评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,257评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,233评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,235评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,940评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,528评论 3 302
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,623评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,858评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,245评论 2 344
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,790评论 2 339

推荐阅读更多精彩内容

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