How to simply retrieve list of Contacts in iOS7?

﹥>﹥吖頭↗ 提交于 2020-01-01 06:56:35

问题


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

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