「透過手機號推薦好友」是社群與支付類 App 的常見套路:客戶端抓取通訊錄裡的所有號碼,送到伺服器換算成各平台的帳號,再回傳一份清單做推薦。這篇文章把 iOS 上讀取通訊錄的四條技術路線整理清楚。
方案一:AddressBookUI.framework
內建聯絡人列表、詳情、新增等界面,通常用來「讓使用者挑選聯絡人」。
方案二:AddressBook.framework
沒有 UI,得自己搭界面;純 C API,資料型別多為 Core Foundation;從 iOS 6 起必須取得使用者授權。
方案三:RHAddressBook
第三方庫,對 AddressBook.framework 做了物件導向封裝。
方案四:Contacts 與 ContactsUI(iOS 9 起)
分別是前兩者的替代品,全面物件導向、使用簡單,ContactsUI 有界面、Contacts 無界面。
1. App 啟動時請求授權
#import "AppDelegate.h"
#import <AddressBook/AddressBook.h>
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[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. iOS 10 需在 Info.plist 補上用途說明
<key>NSContactsUsageDescription</key> <string>請求訪問通訊錄</string>
3. 讀取所有聯絡人
#import "ViewController.h"
#import <AddressBook/AddressBook.h>
@implementation ViewController
- (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(@"firstName=%@, lastName=%@", firstName, lastName);
// 電話(多值)
NSMutableArray *phoneArray = [[NSMutableArray alloc] init];
ABMultiValueRef phones = ABRecordCopyValue(people, kABPersonPhoneProperty);
for (NSInteger j = 0; j < ABMultiValueGetCount(phones); j++) {
NSString *phone = (__bridge NSString *)(ABMultiValueCopyValueAtIndex(phones, j));
[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));
[emailArray addObject:email];
}
NSString *organization = (__bridge NSString *)(ABRecordCopyValue(people, kABPersonOrganizationProperty));
NSString *job = (__bridge NSString *)(ABRecordCopyValue(people, kABPersonJobTitleProperty));
NSString *department = (__bridge NSString *)(ABRecordCopyValue(people, kABPersonDepartmentProperty));
NSString *notes = (__bridge NSString *)(ABRecordCopyValue(people, kABPersonNoteProperty));
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++) {
NSDictionary *tempDic = (__bridge NSDictionary *)(ABMultiValueCopyValueAtIndex(address, j));
NSString *adress = [NSString stringWithFormat:@"國家:%@\n省:%@\n市:%@\n街道:%@\n郵編:%@",
[tempDic valueForKey:(NSString *)kABPersonAddressCountryKey],
[tempDic valueForKey:(NSString *)kABPersonAddressStateKey],
[tempDic valueForKey:(NSString *)kABPersonAddressCityKey],
[tempDic valueForKey:(NSString *)kABPersonAddressStreetKey],
[tempDic valueForKey:(NSString *)kABPersonAddressZIPKey]];
NSLog(@"%@", adress);
}
// 頭像
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));
[dateArr addObject:[NSDictionary dictionaryWithObject:data forKey:str]];
}
}
}
@end
4. 執行結果


https://github.com/heardrwt/RHAddressBook
這個庫是以 MRC 管理記憶體的,直接把原始碼拖進 ARC 專案,得為每個檔案加上 -fno-objc-arc 編譯標記;而且專案年代久遠,部分 API 已被淘汰,實測加完標記仍會報錯。比較可行的做法是把它當成子專案引入:
1. 將 RHAddressBook.xcodeproj 拖進專案。

2. 加入 Target Dependencies 與 Link Binary With Libraries。

3. Build Settings → Other Linker Flags 加上 -ObjC,用來解決系統分類找不到方法的問題。

4. iOS 10 一樣要在 Info.plist 補 NSContactsUsageDescription。
授權請求:
#import <RHAddressBook/RHAddressBook.h>
- (void)requestAuthorizationForAddressBook {
RHAddressBook *ab = [[RHAddressBook alloc] init];
if ([RHAddressBook authorizationStatus] == RHAuthorizationStatusNotDetermined) {
[ab requestAuthorizationWithCompletion:^(bool granted, NSError *error) {
if (granted) { } else { NSLog(@"請求授權拒絕"); }
}];
}
}
讀取聯絡人與電話:
#import <RHAddressBook/RHAddressBook.h>
#import <RHAddressBook/AddressBook.h>
- (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 j = 0; j < phoneNumbers.count; j++) {
NSString *label = [phoneNumbers labelAtIndex:j];
NSString *value = [phoneNumbers valueAtIndex:j];
NSLog(@"label=%@, value=%@", label, value);
}
}
}
執行結果:

#import <ContactsUI/ContactsUI.h>
@interface ViewController () <CNContactPickerDelegate>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
CNContactPickerViewController *picker = [[CNContactPickerViewController alloc] init];
picker.delegate = self;
[self presentViewController:picker animated:YES completion:nil];
}
// 注意:實作了這個方法,選中聯絡人後就不會再進入詳情界面
- (void)contactPicker:(CNContactPickerViewController *)picker
didSelectContact:(CNContact *)contact {
[self printContactInfo:contact];
}
// 多選
- (void)contactPicker:(CNContactPickerViewController *)picker
didSelectContacts:(NSArray<CNContact *> *)contacts {
for (CNContact *contact in contacts) {
[self printContactInfo:contact];
}
}
- (void)printContactInfo:(CNContact *)contact {
NSLog(@"givenName=%@, familyName=%@", contact.givenName, contact.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 { }
@end
單選與多選的界面:



一樣先補用途說明:
<key>NSContactsUsageDescription</key> <string>請求訪問通訊錄</string>
啟動時請求授權:
#import <Contacts/Contacts.h>
- (void)requestAuthorizationForAddressBook {
CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
if (status == CNAuthorizationStatusNotDetermined) {
CNContactStore *contactStore = [[CNContactStore alloc] init];
[contactStore requestAccessForEntityType:CNEntityTypeContacts
completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (granted) { } else { NSLog(@"授權失敗, error=%@", error); }
}];
}
}
讀取資料——這裡有個容易忽略的設計:必須明確指定要取哪些欄位,系統不會給你全部。
#import <Contacts/Contacts.h>
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
if (status != CNAuthorizationStatusAuthorized) {
NSLog(@"沒有授權...");
return;
}
// 獲取指定的字段
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(@"givenName=%@, familyName=%@", contact.givenName, contact.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
}];
}
執行結果:


新專案直接上 Contacts 與 ContactsUI,API 物件導向、不需要處理 Core Foundation 的手動記憶體管理。若只需「讓使用者挑幾個人」,用 ContactsUI 的 picker 最省事;若要背景批次掃描全部聯絡人做比對,則用 Contacts 的 enumerateContactsWithFetchRequest:。AddressBook 系列屬於歷史包袱,維護舊專案時才會碰到。