AddressBook.framework (ABAddressBook) 已在 iOS 9 棄用,iOS 13 移除。新項目必須使用 Contacts.framework (CNContact)。本文僅供維護舊項目參考。
- (void)fetchAllContacts {
// 1. 請求授權 (iOS 6+)
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
if (!granted) {
dispatch_async(dispatch_get_main_queue(), ^{
// 提示用戶去設置開啟權限
});
return;
}
// 2. 獲取所有人
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex count = CFArrayGetCount(allPeople);
NSMutableArray *contacts = [NSMutableArray array];
for (CFIndex i = 0; i < count; i++) {
ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);
NSMutableDictionary *contact = [NSMutableDictionary dictionary];
// 姓名
CFStringRef first = ABRecordCopyValue(person, kABPersonFirstNameProperty);
CFStringRef last = ABRecordCopyValue(person, kABPersonLastNameProperty);
NSString *name = [NSString stringWithFormat:@"%@%@",
(__bridge_transfer NSString *)first ?: @"",
(__bridge_transfer NSString *)last ?: @""];
if (name.length == 0) name = @"無姓名";
contact[@"name"] = name;
// 電話 (多值)
ABMultiValueRef phones = ABRecordCopyValue(person, kABPersonPhoneProperty);
NSMutableArray *phoneList = [NSMutableArray array];
for (CFIndex j = 0; j < ABMultiValueGetCount(phones); j++) {
CFStringRef phone = ABMultiValueCopyValueAtIndex(phones, j);
[phoneList addObject:(__bridge_transfer NSString *)phone];
}
contact[@"phones"] = phoneList;
CFRelease(phones);
// 郵箱
ABMultiValueRef emails = ABRecordCopyValue(person, kABPersonEmailProperty);
NSMutableArray *emailList = [NSMutableArray array];
for (CFIndex j = 0; j < ABMultiValueGetCount(emails); j++) {
CFStringRef email = ABMultiValueCopyValueAtIndex(emails, j);
[emailList addObject:(__bridge_transfer NSString *)email];
}
contact[@"emails"] = emailList;
CFRelease(emails);
// 地址
ABMultiValueRef addresses = ABRecordCopyValue(person, kABPersonAddressProperty);
NSMutableArray *addrList = [NSMutableArray array];
for (CFIndex j = 0; j < ABMultiValueGetCount(addresses); j++) {
CFDictionaryRef addrDict = ABMultiValueCopyValueAtIndex(addresses, j);
NSDictionary *addr = (__bridge_transfer NSDictionary *)addrDict;
[addrList addObject:addr]; // 包含 Street, City, State, ZIP, Country 等鍵
}
contact[@"addresses"] = addrList;
CFRelease(addresses);
[contacts addObject:contact];
}
CFRelease(allPeople);
CFRelease(addressBook);
// 3. 回調主線程
dispatch_async(dispatch_get_main_queue(), ^{
self.contacts = contacts;
[self.tableView reloadData];
});
});
}
import Contacts
func fetchContacts(completion: @escaping ([CNContact]) -> Void) {
let store = CNContactStore()
// 1. 請求權限
store.requestAccess(for: .contacts) { granted, error in
guard granted else { completion([]); return }
// 2. 定義需要的鍵
let keys = [CNContactGivenNameKey, CNContactFamilyNameKey,
CNContactPhoneNumbersKey, CNContactEmailAddressesKey,
CNContactPostalAddressesKey, CNContactThumbnailImageDataKey]
// 3. 統一請求
let request = CNContactFetchRequest(keysToFetch: keys as [CNKeyDescriptor])
var contacts = [CNContact]()
do {
try store.enumerateContacts(with: request) { contact, _ in
contacts.append(contact)
}
completion(contacts)
} catch {
print("Fetch error: \(error)")
completion([])
}
}
}
// 使用
fetchContacts { contacts in
for contact in contacts {
let name = "\(contact.givenName) \(contact.familyName)"
let phones = contact.phoneNumbers.map { $0.value.stringValue }
let emails = contact.emailAddresses.map { $0.value as String }
let addresses = contact.postalAddresses.map { $0.value }
// 更新 UI
}
}
NSContactsUsageDescription
我們需要訪問通訊錄以便您分享聯系人/導入好友
| 特性 | ABAddressBook (舊) | Contacts.framework (新) |
|---|---|---|
| API 風格 | C API (CFTypeRef) | 純 Swift/OC 物件導向 |
| 線程安全 | 需自行管理 | 線程安全 |
| 鍵值獲取 | 硬編碼常量 | 類型安全 KeyDescriptor |
| 多值屬性 | ABMultiValueRef 手動遍歷 | 原生 Swift Array |
| 權限請求 | ABAddressBookRequestAccessWithCompletion | CNContactStore.requestAccess |
| 統一獲取 | 不支援 | enumerateContactsWithFetchRequest 批量高效 |
| iCloud/同步 | 手動處理 | 自動融合統一聯系人 |