objective-c – ABAddressBookGetPersonCount在iOS中返回-1

我遇到ABAddressBookGetPersonCount返回-1的情况.测试人员向我保证地址簿中存在联系人.所有手机都运行iOS 6.0.1.

这是代码:

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);

我无法在我的任何手机上重现这一点,但测试人员尝试过3部手机.它适用于iPhone 5,但不适用于4或3;

我找不到任何表明值为-1的文档.我假设它是某种错误,但是什么?

在iOS 6下,此代码无效.您必须验证您的应用是否有权访问通讯录.最有可能的是,-1表示应用程序在这些设备上没有权限(或未知权限状态).

从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);

如果您需要支持iOS 5.x或4.x,则需要正确检查是否存在新方法.

相关文章
相关标签/搜索