服务器之家

服务器之家 > 正文

详解iOS获取通讯录的4种方式

时间:2021-02-05 15:34     来源/作者:vbirdbest

本文实例为大家分享了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

实现步骤:

1.创建选择联系人的控制器
2.设置代理:用来接收用户选择的联系人信息
3.弹出联系人控制器
4.实现代理方法
5.在对应的代理方法中获取联系人信息

addressbook.frame实现步骤:

1.请求授权
2.判断授权状态如果已授权则继续,如果未授权则提示用户
3.创建通讯录对象
4.从通讯录中获取所有的联系人
5.遍历所有的联系人
6.释放不再使用的对象

addreesbook.framework具体实现:

1. appdelegate 应用启动时请求授权

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#import "appdelegate.h"
#import <addressbook/addressbook.h>
 
@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

2. ios10 需要在info.plist配置nscontactsusagedescription

?
1
2
<key>nscontactsusagedescription</key>
<string>请求访问通讯录</string>

3. viewcontroller

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#import "viewcontroller.h"
#import <addressbook/addressbook.h>
 
@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<abmultivaluegetcount(phones); j++) {
   nsstring *phone = (__bridge nsstring *)(abmultivaluecopyvalueatindex(phones, j));
   nslog(@"phone=%@", phone);
   [phonearray addobject:phone];
  }
 
  //获取当前联系人的邮箱 注意是数组
  nsmutablearray *emailarray = [[nsmutablearray alloc]init];
  abmultivalueref emails= abrecordcopyvalue(people, kabpersonemailproperty);
  for (nsinteger j=0; j<abmultivaluegetcount(emails); j++) {
   nsstring *email = (__bridge nsstring *)(abmultivaluecopyvalueatindex(emails, j));
   nslog(@"email=%@", email);
   [emailarray addobject:email];
  }
//获取当前联系人中间名
  nsstring *middlename=(__bridge nsstring*)(abrecordcopyvalue(people, kabpersonmiddlenameproperty));
  //获取当前联系人的名字前缀
  nsstring *prefix=(__bridge nsstring*)(abrecordcopyvalue(people, kabpersonprefixproperty));
 
  //获取当前联系人的名字后缀
  nsstring *suffix=(__bridge nsstring*)(abrecordcopyvalue(people, kabpersonsuffixproperty));
 
  //获取当前联系人的昵称
  nsstring *nickname=(__bridge nsstring*)(abrecordcopyvalue(people, kabpersonnicknameproperty));
 
  //获取当前联系人的名字拼音
  nsstring *firstnamephoneic=(__bridge nsstring*)(abrecordcopyvalue(people, kabpersonfirstnamephoneticproperty));
 
  //获取当前联系人的姓氏拼音
  nsstring *lastnamephoneic=(__bridge nsstring*)(abrecordcopyvalue(people, kabpersonlastnamephoneticproperty));
 
  //获取当前联系人的中间名拼音
  nsstring *middlenamephoneic=(__bridge nsstring*)(abrecordcopyvalue(people, kabpersonmiddlenamephoneticproperty));
 
  //获取当前联系人的公司
  nsstring *organization=(__bridge nsstring*)(abrecordcopyvalue(people, kabpersonorganizationproperty));
 
  //获取当前联系人的职位
  nsstring *job=(__bridge nsstring*)(abrecordcopyvalue(people, kabpersonjobtitleproperty));
 
  //获取当前联系人的部门
  nsstring *department=(__bridge nsstring*)(abrecordcopyvalue(people, kabpersondepartmentproperty));
 
  //获取当前联系人的生日
  nsstring *birthday=(__bridge nsdate*)(abrecordcopyvalue(people, kabpersonbirthdayproperty));
 
  //获取当前联系人的备注
  nsstring *notes=(__bridge nsstring*)(abrecordcopyvalue(people, kabpersonnoteproperty));
 
  //获取创建当前联系人的时间 注意是nsdate
  nsdate *creattime=(__bridge nsdate*)(abrecordcopyvalue(people, kabpersoncreationdateproperty));
 
  //获取最近修改当前联系人的时间
  nsdate *altertime=(__bridge nsdate*)(abrecordcopyvalue(people, kabpersonmodificationdateproperty));
 
  //获取地址
  abmultivalueref address = abrecordcopyvalue(people, kabpersonaddressproperty);
  for (int j=0; j<abmultivaluegetcount(address); j++) {
   //地址类型
   nsstring *type = (__bridge nsstring *)(abmultivaluecopylabelatindex(address, j));
   nsdictionary * tempdic = (__bridge nsdictionary *)(abmultivaluecopyvalueatindex(address, j));
   //地址字符串,可以按需求格式化
   nsstring *adress = [nsstring stringwithformat:@"国家:%@\n省:%@\n市:%@\n街道:%@\n邮编:%@",[temdic valueforkey:(nsstring*)kabpersonaddresscountrykey],[tempdic valueforkey:(nsstring*)kabpersonaddressstatekey],[tempdic valueforkey:(nsstring*)kabpersonaddresscitykey],[tempdic valueforkey:(nsstring*)kabpersonaddressstreetkey],[tempdic valueforkey:(nsstring*)kabpersonaddresszipkey]];
  }
 
  //获取当前联系人头像图片
  nsdata *userimage=(__bridge nsdata*)(abpersoncopyimagedata(people));
 
  //获取当前联系人纪念日
  nsmutablearray *datearr = [[nsmutablearray alloc]init];
  abmultivalueref dates= abrecordcopyvalue(people, kabpersondateproperty);
  for (nsinteger j=0; j<abmultivaluegetcount(dates); j++) {
   //获取纪念日日期
   nsdate *data =(__bridge nsdate*)(abmultivaluecopyvalueatindex(dates, j));
   //获取纪念日名称
   nsstring *str =(__bridge nsstring*)(abmultivaluecopylabelatindex(dates, j));
   nsdictionary *tempdic = [nsdictionary dictionarywithobject:data forkey:str];
   [datearr addobject:tempdic];
  }
 }
}
 
@end

4. 运行结果

详解iOS获取通讯录的4种方式

详解iOS获取通讯录的4种方式

第三方框架:rhaddressbook

https://github.com/heardrwt/rhaddressbook

该框架使用的mrc来管理内存的,如果直接将源代码拖入进去需要为每个文件设置编译标记:-fno-objc-arc, 设置完还会报错,该项目使用的一些方法过于古老,很多都不支持了,所以这种方式不采用; 可以将该项目打成静态库的方式;也可以直接将项目拖入到自己的工程中作为一个依赖

1.直接将rhaddressbook.xcodeproj拖入到工程中

详解iOS获取通讯录的4种方式

2.添加target dependencies和link binary with libraries

详解iOS获取通讯录的4种方式

3.build settings—> other linker flags : -objc

用于解决系统分类找不到方法的错误

详解iOS获取通讯录的4种方式

4.ios10 需要在info.plist配置nscontactsusagedescription

?
1
2
<key>nscontactsusagedescription</key>
<string>请求访问通讯录</string> 

app启动时请求授权访问通讯录

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#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

获取所有联系人的信息:姓名、手机号等

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#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

运行结果:

详解iOS获取通讯录的4种方式

contactsui.framework

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#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

选择单个联系人时运行效果:

详解iOS获取通讯录的4种方式

详解iOS获取通讯录的4种方式

选择多个联系人的界面:

详解iOS获取通讯录的4种方式

详解iOS获取通讯录的4种方式

contact.framework

ios10 需要在info.plist配置nscontactsusagedescription

?
1
2
<key>nscontactsusagedescription</key>
<string>请求访问通讯录</string> 

应用启动时请求授权:

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#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

获取通讯录信息

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#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

运行效果:

详解iOS获取通讯录的4种方式

详解iOS获取通讯录的4种方式

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

标签:

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部