ABAddressBookCopyArrayOfAllPeople returns empty array on device [closed]

孤街浪徒 提交于 2019-12-13 09:26:03

问题


I develop application on iOS 6 that need access to AddressBook, I'm using following code:

NSMutableArray *contacts = [[NSMutableArray alloc]init];
CFErrorRef *error = nil;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
if (error)
{NSLog(@"ERROR!!!");}
NSArray *arrayOfPeople = (__bridge_transfer NSArray*)ABAddressBookCopyArrayOfAllPeople(addressBook);

but on real device arrayOfPeople is empty...Why is this happening? P.S. All accesses to AddressBook are granted


回答1:


First, here's a rewrite of your code in proper form as a starting place.

CFErrorRef error = nil; // no asterisk
ABAddressBookRef addressBook = 
    ABAddressBookCreateWithOptions(NULL, &error); // indirection
if (!addressBook) // test the result, not the error
{
    NSLog(@"ERROR!!!");
    return; // bail
}
CFArrayRef arrayOfPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
NSLog(@"%@", arrayOfPeople); // let's see how we did

Second, here's the actual cause of your problem: you've no access. At some point you need to have called ABAddressBookRequestAccessWithCompletion to ensure access. Note that this call is asynchronous, so you will need to get the array of people from a separate call, or in the completion handler.

The docs seem to imply that you'll get NULL if there is no access, but this is not the case if access is undetermined. Instead, you get a useless empty read-only address database. Thus the only way to be sure you have access is to check explicitly with ABAddressBookGetAuthorizationStatus, and the only to way to get the request for access alert to appear is to call ABAddressBookRequestAccessWithCompletion.

This might be new iOS 6.1 behavior. It is certainly not how I remember things from iOS 6.0.

This same issue doesn't arise in the Simulator because you are granted access automatically (rather unrealistic - another good reason to test only on the device for this sort of thing).



来源:https://stackoverflow.com/questions/16565645/abaddressbookcopyarrayofallpeople-returns-empty-array-on-device

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!