问题
I need to retrieve list of Contacts
in iOS
.
Here is my code that is not work.
NSMutableArray *myContacts = [[NSMutableArray alloc]init];
CFErrorRef error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
if (addressBook!=nil)
{
NSArray *allContacts = (__bridge_transfer NSArray*)ABAddressBookCopyArrayOfAllPeople(addressBook);
NSUInteger i = 0;
for (i = 0; i<[allContacts count]; i++)
{
Person *person = [[Person alloc] init];
ABRecordRef contactPerson = (__bridge ABRecordRef)allContacts[i];
NSString *firstName = (__bridge_transfer NSString*)ABRecordCopyValue(contactPerson, kABPersonFirstNameProperty);
person.firstName = firstName;
[myContacts addObject:person];
}
CFRelease(addressBook);
}
else
{
NSLog(@"Error");
}
How can i get the list of Contacts
?
回答1:
You need to request access to the user's address book first. Set a flag for checking whether the user allowed/denied access.
__block BOOL userDidGrantAddressBookAccess;
CFErrorRef addressBookError = NULL;
if ( ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined ||
ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized )
{
addressBook = ABAddressBookCreateWithOptions(NULL, &addressBookError);
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error){
userDidGrantAddressBookAccess = granted;
dispatch_semaphore_signal(sema);
});
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}
else
{
if ( ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusDenied ||
ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusRestricted )
{
// Display an error.
}
}
Then you can call that method you wrote to grab the contacts. Remember to check the value of userDidGrantAddressBookAccess
first.
来源:https://stackoverflow.com/questions/19655156/how-to-simply-retrieve-list-of-contacts-in-ios7