大家知道在读取通讯录信息时需要引用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(@"用户未授权提示"); // }不推荐后者得原因是:经过测试(模拟器)后者取得用户授权后并不能立刻执行获取联系人等得相关操作,而前者可以顺利执行。