嗨,我正在申请中使用地址簿。我在模拟器中得到联系人。但在iPhone 4S中,它不会在设备中显示任何联系人。在iPhone 4中,我只收到1个联系人。我不明白为什么它没有显示所有联系人。我正在使用以下代码。请帮帮我。
ABAddressBookRef ab=ABAddressBookCreate();
NSArray *arrTemp=(NSArray *)ABAddressBookCopyArrayOfAllPeople(ab);
UIImage* image;
ContactArray=[[NSMutableArray alloc] init];
for (int i=0;i<[arrTemp count];i++)
{
NSMutableDictionary *dicContact=[[NSMutableDictionary alloc] init];
NSString *str=(NSString *) ABRecordCopyValue([arrTemp objectAtIndex:i], kABPersonFirstNameProperty);
UIImage *imgContactImage=(UIImage *)ABPersonCopyImageDataWithFormat([arrTemp objectAtIndex:i],kABPersonImageFormatOriginalSize);
if(ABPersonHasImageData([arrTemp objectAtIndex:i])){
image = [UIImage imageWithData:(NSData *)ABPersonCopyImageData([arrTemp objectAtIndex:i])];
} else {
image = [UIImage imageNamed:@""];
}
NSString* phoneNumber=@"";
NSString *mobileLabel=@"";
//Get mobile phone number
ABMultiValueRef phoneNumbers = (ABMultiValueRef)ABRecordCopyValue([arrTemp objectAtIndex:i], kABPersonPhoneProperty);
CFRelease(phoneNumbers);
if(ABMultiValueGetCount(phoneNumbers)>0) {
for(CFIndex j = 0; j < ABMultiValueGetCount(phoneNumbers); j++) {
mobileLabel = (NSString*)ABMultiValueCopyLabelAtIndex(phoneNumbers, j);
if([mobileLabel isEqualToString:@"_$!<Mobile>!$_"]) {
phoneNumber = (NSString*)ABMultiValueCopyValueAtIndex(phoneNumbers, j);
}
}
}
else
{
phoneNumber=@"";
}
NSLog(@"%@",phoneNumber);
}
答案 0 :(得分:1)
您是否要求访问iPhone上的联系人?
我在模拟器上遇到过这种情况,不需要问(所有联系人都已加载),但是在设备上,要使这些功能起作用,您必须要求用户授予您访问联系人的权限。 / p>
您可以尝试:
ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
// First time access has been granted, do what you want
});
}
else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
// The user has previously given access, do what you want
}
else {
// The user denied access, ask him to reactive them on the settings
}
然后,你的代码应该可以工作!
答案 1 :(得分:0)
试试这个:
ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);
for (int i = 0; i < nPeople; i++) {
// Get Contact info
ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);
ABRecordID recordID = ABRecordGetRecordID(person);
NSString *firstName = (NSString*)ABRecordCopyValue(person, kABPersonFirstNameProperty);
NSString *lastName = (NSString*)ABRecordCopyValue(person, kABPersonLastNameProperty);
}
不要忘记CF发布您复制的对象。