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?

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top