iOS通讯录开发

文/千煌89(简书作者)
原文链接:http://www.jianshu.com/p/6acad14cf3c9
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。

场景一:直接选择一个联系人的电话号码

这里不需要先获取所有的联系人自己做联系人列表,直接使用系统自带的AddressBookUI/ABPeoplePickerNavigationController.h就好。

首先需要引入如下三个文件

#import <AddressBookUI/ABPeoplePickerNavigationController.h>
#import <AddressBook/ABPerson.h>
#import <AddressBookUI/ABPersonViewController.h>

然后初始化ABPeoplePickerNavigationController。

ABPeoplePickerNavigationController *nav = [[ABPeoplePickerNavigationController alloc] init];
nav.peoplePickerDelegate = self;
if(IOS8_OR_LATER){
    nav.predicateForSelectionOfPerson = [NSPredicate predicateWithValue:false];
}
[self presentViewController:nav animated:YES completion:nil];

在iOS8之后,需要添加nav.predicateForSelectionOfPerson = [NSPredicate predicateWithValue:false];这一段代码,否则选择联系人之后会直接dismiss,不能进入详情选择电话。

最后设置代理

//取消选择
- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker
{
    [peoplePicker dismissViewControllerAnimated:YES completion:nil];
}

iOS8下

- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
    ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
    long index = ABMultiValueGetIndexForIdentifier(phone,identifier);
    NSString *phoneNO = (__bridge NSString *)ABMultiValueCopyValueAtIndex(phone, index);

    if ([phoneNO hasPrefix:@"+"]) {
        phoneNO = [phoneNO substringFromIndex:3];
    }

    phoneNO = [phoneNO stringByReplacingOccurrencesOfString:@"-" withString:@""];
    NSLog(@"%@", phoneNO);
    if (phone && [ZXValidateHelper checkTel:phoneNO]) {
        phoneNum = phoneNO;
        [self.tableView reloadData];
        [peoplePicker dismissViewControllerAnimated:YES completion:nil];
        return;
    }
}

- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person
{
    ABPersonViewController *personViewController = [[ABPersonViewController alloc] init];
    personViewController.displayedPerson = person;
    [peoplePicker pushViewController:personViewController animated:YES];
}

iOS7下

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
    return YES;
}

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
{
    ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
    long index = ABMultiValueGetIndexForIdentifier(phone,identifier);
    NSString *phoneNO = (__bridge NSString *)ABMultiValueCopyValueAtIndex(phone, index);
    if ([phoneNO hasPrefix:@"+"]) {
        phoneNO = [phoneNO substringFromIndex:3];
    }

    phoneNO = [phoneNO stringByReplacingOccurrencesOfString:@"-" withString:@""];
    NSLog(@"%@", phoneNO);
    if (phone && [ZXValidateHelper checkTel:phoneNO]) {
        phoneNum = phoneNO;
        [self.tableView reloadData];
        [peoplePicker dismissViewControllerAnimated:YES completion:nil];
        return NO;
    }
    return YES;
}

效果演示

场景二:读取通讯录

这里需要读取通讯录数据。
首先引入头文件
#import <AddressBook/AddressBook.h>

其次根据权限生成通讯录

- (void)loadPerson
{
    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 *error = NULL;
        ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
        [self copyAddressBook:addressBook];
    }
    else {
        dispatch_async(dispatch_get_main_queue(), ^{
            // 更新界面
            [hud turnToError:@"没有获取通讯录权限"];
        });
    }
}

然后循环获取每个联系人的信息,建议自己建个model存起来。

- (void)copyAddressBook:(ABAddressBookRef)addressBook
{
    CFIndex numberOfPeople = ABAddressBookGetPersonCount(addressBook);
    CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(addressBook);

    for ( int i = 0; i < numberOfPeople; i++){
        ABRecordRef person = CFArrayGetValueAtIndex(people, i);

        NSString *firstName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));
        NSString *lastName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));

      //读取middlename
        NSString *middlename = (NSString*)ABRecordCopyValue(person, kABPersonMiddleNameProperty);
        //读取prefix前缀
        NSString *prefix = (NSString*)ABRecordCopyValue(person, kABPersonPrefixProperty);
        //读取suffix后缀
        NSString *suffix = (NSString*)ABRecordCopyValue(person, kABPersonSuffixProperty);
        //读取nickname呢称
        NSString *nickname = (NSString*)ABRecordCopyValue(person, kABPersonNicknameProperty);
        //读取firstname拼音音标
        NSString *firstnamePhonetic = (NSString*)ABRecordCopyValue(person, kABPersonFirstNamePhoneticProperty);
        //读取lastname拼音音标
        NSString *lastnamePhonetic = (NSString*)ABRecordCopyValue(person, kABPersonLastNamePhoneticProperty);
        //读取middlename拼音音标
        NSString *middlenamePhonetic = (NSString*)ABRecordCopyValue(person, kABPersonMiddleNamePhoneticProperty);
        //读取organization公司
        NSString *organization = (NSString*)ABRecordCopyValue(person, kABPersonOrganizationProperty);
        //读取jobtitle工作
        NSString *jobtitle = (NSString*)ABRecordCopyValue(person, kABPersonJobTitleProperty);
        //读取department部门
        NSString *department = (NSString*)ABRecordCopyValue(person, kABPersonDepartmentProperty);
        //读取birthday生日
        NSDate *birthday = (NSDate*)ABRecordCopyValue(person, kABPersonBirthdayProperty);
        //读取note备忘录
        NSString *note = (NSString*)ABRecordCopyValue(person, kABPersonNoteProperty);
        //第一次添加该条记录的时间
        NSString *firstknow = (NSString*)ABRecordCopyValue(person, kABPersonCreationDateProperty);
        NSLog(@"第一次添加该条记录的时间%@\n",firstknow);
        //最后一次修改該条记录的时间
        NSString *lastknow = (NSString*)ABRecordCopyValue(person, kABPersonModificationDateProperty);
        NSLog(@"最后一次修改該条记录的时间%@\n",lastknow);

        //获取email多值
        ABMultiValueRef email = ABRecordCopyValue(person, kABPersonEmailProperty);
        int emailcount = ABMultiValueGetCount(email);
        for (int x = 0; x < emailcount; x++)
        {
            //获取email Label
            NSString* emailLabel = (NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(email, x));
            //获取email值
            NSString* emailContent = (NSString*)ABMultiValueCopyValueAtIndex(email, x);
        }
        //读取地址多值
        ABMultiValueRef address = ABRecordCopyValue(person, kABPersonAddressProperty);
        int count = ABMultiValueGetCount(address);    

        for(int j = 0; j < count; j++)
        {
            //获取地址Label
            NSString* addressLabel = (NSString*)ABMultiValueCopyLabelAtIndex(address, j);
            //获取該label下的地址6属性
            NSDictionary* personaddress =(NSDictionary*) ABMultiValueCopyValueAtIndex(address, j);
            NSString* country = [personaddress valueForKey:(NSString *)kABPersonAddressCountryKey];
            NSString* city = [personaddress valueForKey:(NSString *)kABPersonAddressCityKey];
            NSString* state = [personaddress valueForKey:(NSString *)kABPersonAddressStateKey];
            NSString* street = [personaddress valueForKey:(NSString *)kABPersonAddressStreetKey];
            NSString* zip = [personaddress valueForKey:(NSString *)kABPersonAddressZIPKey];
            NSString* coutntrycode = [personaddress valueForKey:(NSString *)kABPersonAddressCountryCodeKey];
        }

        //获取dates多值
        ABMultiValueRef dates = ABRecordCopyValue(person, kABPersonDateProperty);
        int datescount = ABMultiValueGetCount(dates);
        for (int y = 0; y < datescount; y++)
        {
            //获取dates Label
            NSString* datesLabel = (NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(dates, y));
            //获取dates值
            NSString* datesContent = (NSString*)ABMultiValueCopyValueAtIndex(dates, y);
        }
        //获取kind值
        CFNumberRef recordType = ABRecordCopyValue(person, kABPersonKindProperty);
        if (recordType == kABPersonKindOrganization) {
            // it‘s a company
            NSLog(@"it‘s a company\n");
        } else {
            // it‘s a person, resource, or room
            NSLog(@"it‘s a person, resource, or room\n");
        }

        //获取IM多值
        ABMultiValueRef instantMessage = ABRecordCopyValue(person, kABPersonInstantMessageProperty);
        for (int l = 1; l < ABMultiValueGetCount(instantMessage); l++)
        {
            //获取IM Label
            NSString* instantMessageLabel = (NSString*)ABMultiValueCopyLabelAtIndex(instantMessage, l);
            //获取該label下的2属性
            NSDictionary* instantMessageContent =(NSDictionary*) ABMultiValueCopyValueAtIndex(instantMessage, l);
            NSString* username = [instantMessageContent valueForKey:(NSString *)kABPersonInstantMessageUsernameKey];

            NSString* service = [instantMessageContent valueForKey:(NSString *)kABPersonInstantMessageServiceKey];
        }

        //读取电话多值
        ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
        for (int k = 0; k<ABMultiValueGetCount(phone); k++)
        {
            //获取电话Label
            NSString * personPhoneLabel = (NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phone, k));
            //获取該Label下的电话值
            NSString * personPhone = (NSString*)ABMultiValueCopyValueAtIndex(phone, k);

        }

        //获取URL多值
        ABMultiValueRef url = ABRecordCopyValue(person, kABPersonURLProperty);
        for (int m = 0; m < ABMultiValueGetCount(url); m++)
        {
            //获取电话Label
            NSString * urlLabel = (NSString*)ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(url, m));
            //获取該Label下的电话值
            NSString * urlContent = (NSString*)ABMultiValueCopyValueAtIndex(url,m);
        }

        //读取照片
        NSData *image = (NSData*)ABPersonCopyImageData(person);

    }
}

效果:

时间: 2024-10-12 20:00:11

iOS通讯录开发的相关文章

iOS 通讯录开发 AddressBook AddressBookUI框架的使用

使用到的系统框架AddressBook,AddressBookUI:IOS中的通讯录是存储在数据库中的,开发人员不能直接访问通讯录数据库,必须依靠AddressBook提供的API来实现通讯录操作,通过AddressBook.FrameWork可以操作通讯录信息,但是AddressBook框架是基于C语言编写的,无法使用ARC管理内存,需要自己手动管理. AddressBook框架的常用类型: ABAddressBookRef:代表通讯录对象.通过该对象,可以直接访问和保存通讯录信息. ABRe

iOS常用开发技巧

iOS开发过程中,总有那么一些个小问题让人纠结,它们不会让程序崩溃,但是会让人崩溃.除此之外,还将分享一些细节现在我通过自己的总结以及从其他地方的引用,来总结一下一些常见小问题. 本篇长期更新,多积累,多奉献,同时感谢其中一些文章的作者的整理,感谢! iOS高级开发实战讲解 这是我在网上搜索到的iOS高级开发实战讲解,由于原文不是很方便浏览,所以我在这里整理一部分出来,方便查阅,同时谢谢原作者. 这里我不是每一个都收录进来,这里只是放出一部分,有些用的太多,我就没整理了,大家如果想看可以去看原文

iOS企业级开发初级课程-表视图(13集)

首先了解了表视图的组成.表视图类的构成.表视图的分类以及表视图的两个重要协议(委托协议和数据源协议),对表视图有了一个整体上的认识.接下来我们掌握了如何实现简单表视图和分节表视图,以及表视图中索引.搜索栏.分组的使用.然后我们学习了如何对表视图单元格进行删除.插入.移动等操作.最后本章向大家介绍了表视图UI设计模式方面的内容. 序号 技术点 1 表视图-1-表视图介绍 2 表视图-2-简单表视图 3 表视图-3-简单表视图下 4 表视图-4-自定义单元格 5 表视图-5-搜索栏-1 6 表视图-

iOS通讯录相关知识-浅析

本文来自于:贞娃儿的博客  http://blog.sina.com.cn/zhenwawaer 在开发一些应用中,我们如果需要iPhone设备中的通讯录信息.或者,需要开发通讯录相关的一些功能.那么就需要了解一下iOS中关于通讯录编程的相关知识. 一.AddressBook.framework-通讯录框架 关于通讯录的相关操作,被集成在AddressBook.framework框架中.所以,我们在使用通讯录相关功能的时候,需要在项目中引入AddressBook.framework框架.并且在需

iOS动画开发之一——UIViewAnimation动画的使用

iOS动画开发之一--UIViewAnimation动画的使用 一.简介 一款APP的成功与否,除了完善的功能外,用户体验也占有极大的比重,动画的合理运用,可以很好的增强用户体验.iOS开发中,常用的动画处理有UIView动画编程和核心动画编程,其中UIView动画使用简便,开发中应用十分广泛.这篇博客,主要讨论UIView的动画使用. 二.UIView动画的几个方法 + (void)animateWithDuration:(NSTimeInterval)duration animations:

cocos2d-x ios游戏开发初认识(五) CCsprite精灵类

这次写一下精灵创建的几种类型: 一.通过文件创建: 在原有的基础上添加如下代码: //一.通过文件创建精灵 CCSprite *bg =CCSprite::create("map.png"); CCSize winSize  =CCDirector::sharedDirector()->getWinSize(); //得到屏幕的尺寸 bg->setPosition(ccp(winSize.width/2, winSize.height/2)); this->addCh

浅谈iOS视频开发

这段时间对视频开发进行了一些了解,在这里和大家分享一下我自己觉得学习步骤和资料,希望对那些对视频感兴趣的朋友有些帮助. 一.iOS系统自带播放器 要了解iOS视频开发,首先我们从系统自带的播放器说起,一.我们可以直接播放视频,看到效果,不然搞了半天还播放不了视频,会让大家失去兴趣.二.其实对于很多需求来说,系统的播放器就能够胜任.简单介绍下 1.MPMoviePlayerController 在iOS中播放视频可以使用MPMoviePlayerController类来完成,具备一般的播放器控制功

iOS常用开发资源整理

在行--专家付费咨询 杂项 App Release Checklist—iOS App发布清单. Hey Focus—帮助你专注于一个任务. Objective Cloud—Objective C App云端服务. Thermal—核心数据编辑器. Big Papoo—替代安装Adhoc App. Tweriod—分析你的推特和followers的推特找出最佳发布时间. Helpscout—用户邮件处理支持. Hipmob—应用内实时聊天. Flat Mobile App Design in P

中文 iOS/Mac 开发博客列表(网址改进)

中文 iOS/Mac 开发博客列表(网址改进) https://github.com/tangqiaoboy/iOSBlogCN 大牛blog: http://blog.devtang.com/ 唐巧 网易微博后台 .猿题库.有道云笔记.粉笔网 http://beyondvincent.com/blog/archives/ 破船 http://onevcat.com/ 王巍 Line 技术领域 :ios+unity3d http://swifter.tips 王巍 swifter 的网站 htt