之前的第一篇文章中介紹了AddressBookUI這個框架,這一篇文章再來看一下AddressBook這個框架论泛,這個框架和前者相比不帶UI揩尸,也就是我們可以從這個框架中獲取到聯(lián)系人相關(guān)數(shù)據(jù),然后根據(jù)數(shù)據(jù)自定義UI界面屁奏。
使用這個框架的話要進(jìn)行授權(quán)岩榆。在AppDelegate中藥執(zhí)行以下代碼:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//要想訪問通訊錄,iOS10之后要在info.plist加上如下字段
// <key>NSContactsUsageDescription</key>
// <string>是否可以訪問通訊錄</string>
//針對AddressBook這個框架坟瓢,自iOS6開始勇边,必選授權(quán)才能上架,否則不能上架
//獲取授權(quán)狀態(tài)
/*
kABAuthorizationStatusNotDetermined = 0, 用戶未選擇
kABAuthorizationStatusRestricted, 一些許可配置阻止了通訊錄的交互kABAuthorizationStatusDenied, 用戶拒絕kABAuthorizationStatusAuthorized 用戶授權(quán)
*/
//1.獲取授權(quán)狀態(tài)
ABAuthorizationStatus state = ABAddressBookGetAuthorizationStatus();
//2.創(chuàng)建 AddressBook
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
//3.沒有授權(quán)時才去授權(quán)
if (state == kABAuthorizationStatusNotDetermined ) {
//請求授權(quán)
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
//3.1 判斷是否出錯
if (error) {
return ;
}
//3.2 判斷是否授權(quán)
if (granted) {
NSLog(@"已經(jīng)授權(quán)");
}else{
NSLog(@"沒有授權(quán)");
}
});
}
//4.釋放CF對象
CFRelease(addressBook);
return YES;
}
接下來看如何獲取聯(lián)系人相關(guān)數(shù)據(jù)折联,和第一篇文章中的部分代碼很類似粒褒,代碼中好友注釋。
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//點擊屏幕 獲取所有聯(lián)系人信息
//1.判斷是否授權(quán)成功诚镰,授權(quán)成功才能獲取數(shù)據(jù)
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
//2.創(chuàng)建通訊錄
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
//3.聯(lián)系人 --->Array
CFArrayRef persons = ABAddressBookCopyArrayOfAllPeople(addressBook);
//4.獲取聯(lián)系人個數(shù)
CFIndex count = CFArrayGetCount(persons);
//遍歷聯(lián)系人
for (CFIndex i = 0; i < count; i++) {
//5.獲取單個聯(lián)系人數(shù)據(jù)
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 獲取電話個數(shù) phones.count不可以獲取個數(shù)
CFIndex count = ABMultiValueGetCount(phones);
//7.2 遍歷聯(lián)系人
for (CFIndex i = 0 ; i < count; i++) {
//7.3 獲取聯(lián)系電話的標(biāo)簽
//兩種寫法
NSString *label = (__bridge_transfer NSString *)ABMultiValueCopyLabelAtIndex(phones, i);
//NSString *label = CFBridgingRelease(ABMultiValueCopyLabelAtIndex(phones, i));
NSLog(@"電話標(biāo)簽:%@",label);//_$!<Home>!$_
//7.4 獲取聯(lián)系人電話
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(@"請前往設(shè)置中更改權(quán)限");
}
}