讀取通訊錄資訊時需要引用 AddressBook、AddressBookUI 框架,然後才能進行相關操作。但在 iOS 7 中不能像 iOS 6 那樣直接讀取通訊錄,而是需要在程式碼中取得使用者授權後才能操作。
推薦使用如下方式:
CFErrorRef *error = nil;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
__block BOOL accessGranted = NO;
if (ABAddressBookRequestAccessWithCompletion != NULL) {
// iOS 6 以上
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
accessGranted = granted;
dispatch_semaphore_signal(sema);
});
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
} else {
// iOS 5 或更舊
accessGranted = YES;
}
if (accessGranted) {
NSMutableArray *addressBookTemp = [NSMutableArray array];
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);
for (NSInteger i = 0; i < nPeople; i++) {
TKAddressBook *addressBook = [[TKAddressBook alloc] init];
ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);
CFStringRef abName = ABRecordCopyValue(person, kABPersonFirstNameProperty);
CFStringRef abLastName = ABRecordCopyValue(person, kABPersonLastNameProperty);
CFStringRef abFullName = ABRecordCopyCompositeName(person);
// ......
}
}
網上還有一種版本:
// CFErrorRef *error = nil;
// ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
//
// __block BOOL accessGranted = NO;
//
// if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
// ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
// accessGranted = granted;
// });
// } else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
// accessGranted = YES;
// } else {
// NSLog(@"用戶未授權提示");
// }
不推薦後者的原因是:經過測試(模擬器),後者在取得使用者授權後並不能立刻執行獲取聯絡人等相關操作,而前者可以順利執行。