我一直在尝试设置一种方法来获取用户通讯录中所有人的姓名以及他们的(多个)电话号码,但我的尝试并没有起作用,当我记录应该包含联系人姓名的数组时,它返回NULL。
以下是我正在使用的代码。此外,我已导入通讯簿的正确支持文件。我确实感觉数组因为addressBook的创建方式而返回null,但我不确定是否是这种情况或如何修复它。任何帮助都非常有用!
//main code
- (void)getPersonOutOfAddressBook
{
CFErrorRef error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
if (addressBook != nil) {
NSLog(@"Succesful.");
NSArray *allContacts = (__bridge_transfer NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
//testing. This returns NULL
NSLog(@"%@", allContacts);
NSUInteger i = 0;
for (i = 0; i < [allContacts count]; i++)
{
ABRecordRef contactPerson = (__bridge ABRecordRef)allContacts[i];
NSString *firstName = (__bridge_transfer NSString *)ABRecordCopyValue(contactPerson,kABPersonFirstNameProperty);
NSString *lastName = (__bridge_transfer NSString *)ABRecordCopyValue(contactPerson, kABPersonLastNameProperty);
NSString *fullName = [NSString stringWithFormat:@"%@ %@", firstName, lastName];
}
CFRelease(addressBook);
} else {
NSLog(@"Error reading Address Book");
}
}
//checking if access is allowed
- (void)checkForAddressBookAccess
{
ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(nil, nil);
if (ABAddressBookRequestAccessWithCompletion == NULL)
{
// iOS5
[self getPersonOutOfAddressBook];
return;
}
else
{
// iOS6
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined)
{
ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
if(error)
{
//error
}
else
{
[self getPersonOutOfAddressBook];
}
});
}
else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized)
{
[self getPersonOutOfAddressBook];
}
else
{
//error
}
}
}