1

嗨,我在我的应用程序中使用地址簿。我在模拟器中获得联系人。但在 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);
}
4

2 回答 2

1

您是否要求访问 iPhone 上的联系人?

我体验过,在模拟器上,不需要询问(所有联系人都已加载),但在设备上,要使这些功能正常工作,您必须要求用户授予您访问他的联系人的权限。

你可以试试 :

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
}

然后,您的代码应该可以工作!

于 2013-01-15T11:41:03.270 回答
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);
}

不要忘记 CFRelease 您复制的对象。

于 2012-06-01T08:58:42.773 回答