如何简单地检索iOS7中的联系人列表?

时间:2013-10-29 10:10:45

标签: ios addressbook

我需要在Contacts中检索iOS的列表。

这是我的代码无效。

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

    }

如何获取Contacts的列表?

1 个答案:

答案 0 :(得分:6)

您需要先请求访问用户的地址簿。设置一个标志,用于检查用户是否允许/拒绝访问。

__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.
    }
}

然后你可以调用你编写的方法来获取联系人。请务必先检查userDidGrantAddressBookAccess的值。