我需要在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
的列表?
答案 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
的值。