ABAddressBookGetPersonCount returns -1 in iOS

I came across a situation where ABAddressBookGetPersonCount returns -1. The tester assures me that there are contacts in the address book. All phones are running iOS 6.0.1.

Here is the code:

NSMutableDictionary *myAddressBook = [[NSMutableDictionary alloc] init]; ABAddressBookRef addressBook = ABAddressBookCreate(); CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(addressBook); int numEntries = ABAddressBookGetPersonCount(addressBook); if (numEntries == 0) { NSString *title = NSLocalizedString(@"error", nil); NSString *description = NSLocalizedString(@"error_empty_contacts", nil); UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:description delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; return; } NSLog(@"emails: found %d", numEntries); 

I can not reproduce this on any of my phones, but the tester tried on 3 phones. It works correctly on iPhone 5, but not on 4 or 3;

I can not find any documents indicating what the value -1 means. I suppose this is some kind of mistake, but what?

+5
ios objective-c
Nov 14 '12 at 2:01
source share
1 answer

In iOS 6, this code is not valid. You must ensure that your application has permission to access the address book. Most likely, -1 indicates that the application does not have permission (or an unknown permission state) on these devices.

From the docs for ABAddressBookRequestAccessCompletionHandler :

 CFErrorRef myError = NULL; ABAddressBookRef myAddressBook = ABAddressBookCreateWithOptions(NULL, &myError); APLViewController * __weak weakSelf = self; // avoid capturing self in the block ABAddressBookRequestAccessWithCompletion(myAddressBook, ^(bool granted, CFErrorRef error) { if (granted) { NSArray *theSmiths = CFBridgingRelease( ABAddressBookCopyPeopleWithName(myAddressBook, CFSTR("Smith") ) ); weakSelf.numberOfSmiths = [theSmiths count]; } else { // Handle the error } }); CFRelease(myAddressBook); 

If you need to support iOS 5.x or 4.x, you need to correctly check for new methods.

+3
Nov 14 '12 at 2:19
source share



All Articles