IOS开发入门iOS 获取通讯录的4种方式详解
白羽 2019-07-10 来源 :网络 阅读 980 评论 0

摘要:本文将带你了解IOS开发入门iOS 获取通讯录的4种方式详解,希望本文对大家学IOS有所帮助。

    本文将带你了解IOS开发入门iOS 获取通讯录的4种方式详解,希望本文对大家学IOS有所帮助。

IOS开发入门iOS 获取通讯录的4种方式详解

使用场景
   一些App通过手机号码来推荐好友,如 微博、支付宝
   首先客户端会获取通讯录中的所有手机号然后将这些手机号提交到App服务器中,服务器会查找每个手机号对应的App账号如QQ号码返回到客户端,然后客户端根据服务器返回的账号列表来推荐好友。
   获取联系人方式
   方案一:AddressBookUI.framework框架
   提供了联系人列表界面、联系人详情界面、添加联系人界面等 一般用于选择联系人 方案二:AddressBook.framework框架:
   没有提供UI界面,需要自己搭建联系人界面 纯C语言的API, 仅仅是获得联系人数据 大部分数据类型是Core Foundation 从iOS6  开始,需要得到用户的授权才能访问通讯录 方案三:第三方框架:RHAddressBook
   对 AddressBook.framework 进行封装 方案四:iOS9.0最新通讯录框架
   ContactsUI.framework : 方案1的替代品,特点: 面向对象,使用简单,有界面 Contacts.framework:  方案2的替代品, 特点:面向对象,使用简单,五界面
   方案一:AddressBookUI.framework
   实现步骤:
   创建选择联系人的控制器 设置代理:用来接收用户选择的联系人信息 弹出联系人控制器 实现代理方法 在对应的代理方法中获取联系人信息
   AddressBook.frame
   实现步骤:
   请求授权 判断授权状态如果已授权则继续,如果未授权则提示用户 创建通讯录对象 从通讯录中获取所有的联系人 遍历所有的联系人  释放不再使用的对象
   AddreesBook.framework具体实现:
   1. AppDelegate 应用启动时请求授权
   ?123456789101112131415161718192021222324252627282930313233#import  "AppDelegate.h"#import @interface AppDelegate  () @end @implementation AppDelegate -  (BOOL)application:(UIApplication *)application  didFinishLaunchingWithOptions:(NSDictionary *)launchOptions  {    // Override point for customization after  application launch.     [self requestAuthorizationAddressBook];    return  YES;}  - (void)requestAuthorizationAddressBook  {    //  判断是否授权    ABAuthorizationStatus authorizationStatus =  ABAddressBookGetAuthorizationStatus();    if  (authorizationStatus == kABAuthorizationStatusNotDetermined)  {        //  请求授权        ABAddressBookRef  addressBookRef =  ABAddressBookCreate();        ABAddressBookRequestAccessWithCompletion(addressBookRef,  ^(bool granted, CFErrorRef error)  {            if  (granted) {  // 授权成功             }  else {        //  授权失败                NSLog(@"授权失败!");            }        });    }}@end</addressbook>
   
   2. iOS10 需要在Info.plist配置NSContactsUsageDescription
   ?12<key>NSContactsUsageDescription</key><string>请求访问通讯录</string>
   
   3. ViewController
   ?123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051#import  "ViewController.h"#import @interface ViewController  () @end @implementation ViewController - (void)viewDidLoad  {    [super viewDidLoad];} -  (void)touchesBegan:(NSSet<uitouch> *)touches withEvent:(UIEvent *)event  {    // 1.  判读授权    ABAuthorizationStatus authorizationStatus =  ABAddressBookGetAuthorizationStatus();    if  (authorizationStatus != kABAuthorizationStatusAuthorized)  {         NSLog(@"没有授权");        return;    }     //  2. 获取所有联系人    ABAddressBookRef addressBookRef =  ABAddressBookCreate();    CFArrayRef arrayRef =  ABAddressBookCopyArrayOfAllPeople(addressBookRef);    long  count = CFArrayGetCount(arrayRef);    for (int i = 0; i  < count; i++) {        //获取联系人对象的引用        ABRecordRef  people = CFArrayGetValueAtIndex(arrayRef,  i);         //获取当前联系人名字        NSString  *firstName=(__bridge NSString *)(ABRecordCopyValue(people,  kABPersonFirstNameProperty));         //获取当前联系人姓氏        NSString  *lastName=(__bridge NSString *)(ABRecordCopyValue(people,  kABPersonLastNameProperty));        NSLog(@"--------------------------------------------------");        NSLog(@"firstName=%@,  lastName=%@", firstName,  lastName);         //获取当前联系人的电话  数组        NSMutaleArray *phoneArray =  [[NSMutableArray  alloc]init];        ABMultiValueRef  phones = ABRecordCopyValue(people,  kABPersonPhoneProperty);        for  (NSInteger j=0; j<hr><h3 id="4-运行结果">4.  运行结果</h3><p><img style="height: 560px; width: 304.79px;"  alt="这里写图片描述"  src="https://www.2cto.com/uploadfile/Collfiles/20161025/20161025092809869.png"  title="\"></p><p><img style="width: 630px;  height: 405.571px;" alt="这里写图片描述" src="https://www.2cto.com/uploadfile/Collfiles/20161025/20161025092809871.png"  title="\"></p><hr><h1  id="第三方框架rhaddressbook">第三方框架:RHAddressBook</h1><hr><p>https://github.com/heardrwt/RHAddressBook</p><p>该框架使用的MRC来管理内存的,如果直接将源代码拖入进去需要为每个文件设置编译标记:-fno-objc-arc,  设置完还会报错,该项目使用的一些方法过于古老,很多都不支持了,所以这种方式不采用;  可以将该项目打成静态库的方式;也可以直接将项目拖入到自己的工程中作为一个依赖</p><p>直接将RHAddressBook.xcodeproj拖入到工程中   <img style="width: 255px; height: 314px;"  alt="这里写图片描述"  src="https://www.2cto.com/uploadfile/Collfiles/20161025/20161025092809872.png"  title="\"></p><p>添加Target Dependencies和Link Binary  With Libraries  <img style="width: 630px; height:  332.308px;" alt="这里写图片描述"  src="https://www.2cto.com/uploadfile/Collfiles/20161025/20161025092809874.png"  title="\"></p><p>Build Settings—> Other Linker  Flags :  -ObjC  用于解决系统分类找不到方法的错误  <img style="width:  630px; height: 209.692px;" alt="这里写图片描述"  src="https://www.2cto.com/uploadfile/Collfiles/20161025/20161025092809879.png"  title="\"></p><p>iOS10 需要在Info.plist配置NSContactsUsageDescription<喎�"https://www.2cto.com/kf/ware/vc/"  target="_blank"  class="keylink">vcD48cHJlIGNsYXNzPQ=="brush:java;"><key>NSContactsUsageDescription</key><string>请求访问通讯录</string>      </p></abmultivaluegetcount(phones);></uitouch></addressbook>
   App启动时请求授权访问通讯录
   ?123456789101112131415161718192021222324252627282930#import  "AppDelegate.h"#import <rhaddressbook  rhaddressbook.h=""> @interface AppDelegate  () @end @implementation AppDelegate -  (BOOL)application:(UIApplication *)application  didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    //  Override point for customization after application  launch.     [self  requestAuthorizationForAddressBook];    return  YES;} - (void)requestAuthorizationForAddressBook {    RHAddressBook  *ab = [[RHAddressBook alloc] init];    if ([RHAddressBook  authorizationStatus] ==  RHAuthorizationStatusNotDetermined){         [ab  requestAuthorizationWithCompletion:^(bool granted, NSError *error)  {            if  (granted)  {             }  else {                NSLog(@"请求授权拒绝");            }        }];    }}@end</rhaddressbook>
   获取所有联系人的信息:姓名、手机号等
   ?12345678910111213141516171819202122232425262728293031323334353637#import  "ViewController.h"#import <rhaddressbook  rhaddressbook.h="">#import <rhaddressbook  addressbook.h=""> @interface ViewController  () @end @implementation ViewController- (void)viewDidLoad  {    [super viewDidLoad];} -  (void)touchesBegan:(NSSet<uitouch> *)touches withEvent:(UIEvent *)event  {    RHAddressBook *addressBook = [[RHAddressBook alloc]  init];    if ([RHAddressBook authorizationStatus] !=  RHAuthorizationStatusAuthorized){        NSLog(@"没有授权");        return;    }     NSArray  *peopleArray= addressBook.people;    for (int i = 0; i  < peopleArray.count; i++) {        RHPerson  *people = (RHPerson  *)peopleArray[i];        NSLog(@"%@",  people.name);         RHMultiStringValue  *phoneNumbers = people.phoneNumbers;        for  (int i = 0; i < phoneNumbers.count; i++)  {            NSString*  label= [phoneNumbers  labelAtIndex:i];            NSString*  value= [phoneNumbers  valueAtIndex:i];             NSLog(@"label=%@,  value=%@", label, value);        }         NSLog(@"----------------------------------------------");    }}@end</uitouch></rhaddressbook></rhaddressbook>
   运行结果:
   
   
   ContactsUI.framework
   
   ?12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152#import  "ViewController.h"#import <contactsui  contactsui.h=""> @interface ViewController ()  <cncontactpickerdelegate> @end @implementation  ViewController - (void)viewDidLoad {    [super  viewDidLoad];     CNContactPickerViewController  *contactPickerViewController = [[CNContactPickerViewController alloc]  init];    contactPickerViewController.delegate =  self;     [self  presentViewController:contactPickerViewController animated:YES  completion:nil];}  // 如果实现该方法当选中联系人时就不会再出现联系人详情界面,  如果需要看到联系人详情界面只能不实现这个方法,- (void)contactPicker:(CNContactPickerViewController  *)picker didSelectContact:(CNContact *)contact  {    NSLog(@"选中某一个联系人时调用---------------------------------");     [self  printContactInfo:contact];} // 同时选中多个联系人-  (void)contactPicker:(CNContactPickerViewController *)picker  didSelectContacts:(NSArray<cncontact> *)contacts  {    for (CNContact *contact in contacts) {        NSLog(@"================================================");        [self  printContactInfo:contact];    }} -  (void)printContactInfo:(CNContact *)contact {    NSString  *givenName = contact.givenName;    NSString *familyName =  contact.familyName;    NSLog(@"givenName=%@,  familyName=%@", givenName, familyName);    NSArray *  phoneNumbers = contact.phoneNumbers;    for  (CNLabeledValue<cnphonenumber*>*phone in phoneNumbers)  {        NSString *label =  phone.label;        CNPhoneNumber  *phonNumber = (CNPhoneNumber  *)phone.value;        NSLog(@"label=%@,  value=%@", label, phonNumber.stringValue);    }}//  注意:如果实现该方法,上面那个方法就不能实现了,这两个方法只能实现一个//-  (void)contactPicker:(CNContactPickerViewController *)picker  didSelectContactProperty:(CNContactProperty *)contactProperty  {//     NSLog(@"选中某个联系人的某个属性时调用");//} @end</cnphonenumber*></cncontact></cncontactpickerdelegate></contactsui>
   选择单个联系人时运行效果:
   
   
   选择多个联系人的界面:
   
   
   
   Contact.framework
   
   iOS10 需要在Info.plist配置NSContactsUsageDescription
   ?12<key>NSContactsUsageDescription</key><string>请求访问通讯录</string>
   
   应用启动时请求授权:
   ?1234567891011121314151617181920212223242526272829303132#import  "AppDelegate.h"#import <contacts  contacts.h=""> @interface AppDelegate () @end @implementation  AppDelegate  - (BOOL)application:(UIApplication *)application  didFinishLaunchingWithOptions:(NSDictionary *)launchOptions  {    // Override point for customization after  application launch.     [self  requestAuthorizationForAddressBook];    return  YES;} - (void)requestAuthorizationForAddressBook  {    CNAuthorizationStatus authorizationStatus =  [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];    if  (authorizationStatus == CNAuthorizationStatusNotDetermined)  {        CNContactStore *contactStore  = [[CNContactStore alloc] init];        [contactStore  requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL  granted, NSError * _Nullable error)  {            if  (granted) {             }  else  {                NSLog(@"授权失败,  error=%@", error);            }        }];    }} @end</contacts>
   
   获取通讯录信息
   ?1234567891011121314151617181920212223242526272829303132333435363738394041424344#import  "ViewController.h"#import <contacts  contacts.h=""> @interface ViewController  () @end @implementation ViewController - (void)viewDidLoad  {    [super viewDidLoad]; } - (void)touchesBegan:(NSSet<uitouch>  *)touches withEvent:(UIEvent *)event  {    CNAuthorizationStatus authorizationStatus =  [CNContactStore  authorizationStatusForEntityType:CNEntityTypeContacts];    if  (authorizationStatus == CNAuthorizationStatusAuthorized)  {        NSLog(@"没有授权...");    }     //  获取指定的字段,并不是要获取所有字段,需要指定具体的字段    NSArray *keysToFetch = @[CNContactGivenNameKey,  CNContactFamilyNameKey,  CNContactPhoneNumbersKey];    CNContactFetchRequest  *fetchRequest = [[CNContactFetchRequest alloc]  initWithKeysToFetch:keysToFetch];    CNContactStore  *contactStore = [[CNContactStore alloc]  init];    [contactStore  enumerateContactsWithFetchRequest:fetchRequest error:nil  usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop)  {        NSLog(@"-------------------------------------------------------");        NSString  *givenName =  contact.givenName;        NSString  *familyName = contact.familyName;        NSLog(@"givenName=%@,  familyName=%@", givenName,  familyName);          NSArray  *phoneNumbers =  contact.phoneNumbers;        for  (CNLabeledValue *labelValue in phoneNumbers)  {            NSString  *label =  labelValue.label;            CNPhoneNumber  *phoneNumber =  labelValue.value;             NSLog(@"label=%@,  phone=%@", label,  phoneNumber.stringValue);        } //         *stop = YES;  //  停止循环,相当于break;    }]; }@end</uitouch></contacts>
   
   运行效果:    

本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标移动开发之IOS频道!

本文由 @白羽 发布于职坐标。未经许可,禁止转载。
喜欢 | 0 不喜欢 | 0
看完这篇文章有何感觉?已经有0人表态,0%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    ICP许可  沪B2-20190160

©2015 www.zhizuobiao.com All Rights Reserved

208小时内训课程