大家知道在讀取通訊錄信息時需要引用AddressBook、AddressBookUI得框架,然後就可以進行相關操作。但是在iOS7中不能夠像iOS6中直接讀取通訊錄信息,而是需要代碼中取得用戶授權才可以進行相關操作。
推薦使用如下方式:
CFErrorRef *error = nil; ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error); __block BOOL accessGranted = NO; if (ABAddressBookRequestAccessWithCompletion != NULL) { // we're on 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 { // we're on iOS 5 or older accessGranted = YES; }
另外,網上還有一種版本if (accessGranted) {
NSMutableArray *addressBookTemp = [NSMutableArray array];
//ABAddressBookRef addressBooks = ABAddressBookCreate();
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(@"用戶未授權提示"); // }不推薦後者得原因是:經過測試(模擬器)後者取得用戶授權後並不能立刻執行獲取聯系人等得相關操作,而前者可以順利執行。