我使用了以下代码块来检索联系人。问题是,没有赋值,它似乎在“contacts”数组中,如最后预期的那样。我是iOS新手中的新手。如果有人可以帮助我,谢谢你。
CFErrorRef * error = NULL;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error)
{
if (granted)
{
dispatch_async(dispatch_get_main_queue(), ^{
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex numberOfPeople = ABAddressBookGetPersonCount(addressBook);
for(int i = 0; i < numberOfPeople; i++){
ABRecordRef person = CFArrayGetValueAtIndex( allPeople, i );
NSString *firstName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty));
NSString *lastName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty));
NSString *name = [NSString stringWithFormat:@"%@ %@", firstName, lastName];
ABMultiValueRef emails = ABRecordCopyValue(person, kABPersonEmailProperty);
NSUInteger j = 0;
if (emails) {
for (j = 0; j < ABMultiValueGetCount(emails); j++) {
NSString *email = (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(emails, j);
if (j == 0) {
[emailConatcts setValue:email forKey:name];
[contacts addObject:emailConatcts];
}
}
}
ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
if (phoneNumbers) {
CFIndex numberOfPhoneNumbers = ABMultiValueGetCount(phoneNumbers);
for (CFIndex i = 0; i < numberOfPhoneNumbers; i++) {
CFStringRef label = ABMultiValueCopyLabelAtIndex(phoneNumbers, i);
if (label) {
if (CFEqual(label, kABPersonPhoneMobileLabel)) {
NSString *phoneNumber = (__bridge_transfer NSString *) ABMultiValueCopyValueAtIndex(phoneNumbers, i);
[mobileContacts setValue:phoneNumber forKey:name];
[contacts addObject:emailConatcts];
}
}
}
}
}
});
}
});
NSLog(@"contacts: %@", contacts);
答案 0 :(得分:0)
在您明确拥有联系人之前,您正在询问联系人。 如果你移动这一行
NSLog(@"contacts: %@", contacts);
之前
});
}
});
你应该看到数据。
原因是,当您使用dispach和completion块时,您告诉系统在某个操作完成后运行该代码(通常在不同的线程中)。因此,当您打印联系人时,该阻止代码尚未运行。
所以无论你需要对联系人做什么,都要在那个区块内调用它:)