You know that when reading the address book information, you need to reference the AddressBook and AddressBookUI frameworks, and then you can perform related operations. However, in iOS7, the address book information cannot be directly read like in iOS6, but operations can be performed only when user authorization is obtained in the code.
The following method is recommended:
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);
}
...................................
}
There is also a version on the Internet
// CFErrorRef * error = nil; // ABAddressBookRef addressBook = abaddressbookcreatewitexceptions (NULL, error); // _ block BOOL accessGranted = NO; /// if (ABAddressBookGetAuthorizationStatus () = kABAuthorizationStatusNotDetermined) {// register (addressBook, ^ (bool granted, CFErrorRef error) {// accessGranted = granted; //}); // else if (ABAddressBookGetAuthorizationStatus () = kABAuthorizationStatusAuthorized) {// accessGranted = YES; //} // else // {// NSLog (@ "User unauthorized prompt ");//}
The reason for not recommending the latter is: after testing (simulator), the latter cannot immediately perform operations such as obtaining contacts after obtaining user authorization, and the former can perform smoothly.