之前的第一篇文章中介绍了AddressBookUI这个框架,这一篇文章再来看一下AddressBook这个框架,这个框架和前者相比不带UI,也就是我们可以从这个框架中获取到联系人相关数据,然后根据数据自定义UI界面。
使用这个框架的话要进行授权。在AppDelegate中药执行以下代码:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//要想访问通讯录,iOS10之后要在info.plist加上如下字段
// <key>NSContactsUsageDescription</key>
// <string>是否可以访问通讯录</string>
//针对AddressBook这个框架,自iOS6开始,必选授权才能上架,否则不能上架
//获取授权状态
/*
kABAuthorizationStatusNotDetermined = 0, 用户未选择
kABAuthorizationStatusRestricted, 一些许可配置阻止了通讯录的交互kABAuthorizationStatusDenied, 用户拒绝kABAuthorizationStatusAuthorized 用户授权
*/
//1.获取授权状态
ABAuthorizationStatus state = ABAddressBookGetAuthorizationStatus();
//2.创建 AddressBook
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
//3.没有授权时才去授权
if (state == kABAuthorizationStatusNotDetermined ) {
//请求授权
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
//3.1 判断是否出错
if (error) {
return ;
}
//3.2 判断是否授权
if (granted) {
NSLog(@"已经授权");
}else{
NSLog(@"没有授权");
}
});
}
//4.释放CF对象
CFRelease(addressBook);
return YES;
}
接下来看如何获取联系人相关数据,和第一篇文章中的部分代码很类似,代码中好友注释。
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//点击屏幕 获取所有联系人信息
//1.判断是否授权成功,授权成功才能获取数据
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
//2.创建通讯录
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
//3.联系人 --->Array
CFArrayRef persons = ABAddressBookCopyArrayOfAllPeople(addressBook);
//4.获取联系人个数
CFIndex count = CFArrayGetCount(persons);
//遍历联系人
for (CFIndex i = 0; i < count; i++) {
//5.获取单个联系人数据
ABRecordRef person = CFArrayGetValueAtIndex(persons, i);
//6.获取姓名
NSString *lastName = CFBridgingRelease(ABRecordCopyValue(person, kABPersonLastNameProperty));
NSString *firstName = CFBridgingRelease(ABRecordCopyValue(person, kABPersonFirstNameProperty));
NSLog(@"姓:%@ 名:%@",lastName,firstName);
//7.获取电话
ABMultiValueRef phones = ABRecordCopyValue(person, kABPersonPhoneProperty);
//7.1 获取电话个数 phones.count不可以获取个数
CFIndex count = ABMultiValueGetCount(phones);
//7.2 遍历联系人
for (CFIndex i = 0 ; i < count; i++) {
//7.3 获取联系电话的标签
//两种写法
NSString *label = (__bridge_transfer NSString *)ABMultiValueCopyLabelAtIndex(phones, i);
//NSString *label = CFBridgingRelease(ABMultiValueCopyLabelAtIndex(phones, i));
NSLog(@"电话标签:%@",label);//_$!<Home>!$_
//7.4 获取联系人电话
NSString *value =(__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(phones, i);
NSLog(@"电话号码:%@",value);
}
NSLog(@"\n\n");
//8.释放CF对象
CFRelease(phones);
}
//8.释放CF对象
CFRelease(persons);
CFRelease(addressBook);
}else{
NSLog(@"请前往设置中更改权限");
}
}