在iOS 7中获取联系人

26

这段代码在 iOS5/iOS6 上运行良好,但在 iOS7 上无法正常工作。

CFErrorRef *error = NULL;
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
    //ABAddressBookRef addressBook = ABAddressBookCreate();
    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));
     //   NSLog(@"Name:%@ %@", firstName, lastName);

        ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
        NSString *phoneNumber;
        for (CFIndex i = 0; i < ABMultiValueGetCount(phoneNumbers); i++) {
            phoneNumber = (__bridge_transfer NSString *) ABMultiValueCopyValueAtIndex(phoneNumbers, i);
            //   NSLog(@"phone:%@", phoneNumber);
        }

2
在iOS 7上会发生什么事情? - Christian Schnorr
CFArrayRef不会返回数组,总是返回一个空数组。 - DipakSonara
1
你是在模拟器上测试还是在设备上测试?我注意到iOS模拟器默认没有联系人。当我添加了一个联系人后,很明显代码确实适用于iOS 6和7两个版本。 - Paaske
1
Paaske,你是对的!难以置信的是,在更新到XCODE 5.0.2之后,模拟器的地址簿变空了!以前,你总是可以用标准联系人“John Appleseed”等测试你的应用程序。现在,每次重置模拟器都必须手动输入自己的地址! - Reinhard Männer
1
我在这里发布了Swift版本:https://dev59.com/um865IYBdhLWcg3wkfcW#33219114 - Bojan Bozovic
显示剩余2条评论
2个回答

66

今天更新了我的示例并修复了内存泄漏问题 :)

 + (NSArray *)getAllContacts {

    CFErrorRef *error = nil;
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
    ABRecordRef source = ABAddressBookCopyDefaultSource(addressBook);
    CFArrayRef allPeople = (ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(addressBook, source, kABPersonSortByFirstName));
    //CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);
      CFIndex nPeople = CFArrayGetCount(allPeople); // bugfix who synced contacts with facebook
    NSMutableArray* items = [NSMutableArray arrayWithCapacity:nPeople];

    if (!allPeople || !nPeople) {
        NSLog(@"people nil");
    }


    for (int i = 0; i < nPeople; i++) {

        @autoreleasepool {

            //data model
            ContactsData *contacts = [ContactsData new];

            ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);

            //get First Name
            CFStringRef firstName = (CFStringRef)ABRecordCopyValue(person,kABPersonFirstNameProperty);
            contacts.firstNames = [(__bridge NSString*)firstName copy];

            if (firstName != NULL) {
                CFRelease(firstName);
            }


            //get Last Name
            CFStringRef lastName = (CFStringRef)ABRecordCopyValue(person,kABPersonLastNameProperty);
            contacts.lastNames = [(__bridge NSString*)lastName copy];

            if (lastName != NULL) {
                CFRelease(lastName);
            }


            if (!contacts.firstNames) {
                contacts.firstNames = @"";
            }

            if (!contacts.lastNames) {
                contacts.lastNames = @"";
            }



            contacts.contactId = ABRecordGetRecordID(person);
            //append first name and last name
            contacts.fullname = [NSString stringWithFormat:@"%@ %@", contacts.firstNames, contacts.lastNames];


            // get contacts picture, if pic doesn't exists, show standart one
            CFDataRef imgData = ABPersonCopyImageData(person);
            NSData *imageData = (__bridge NSData *)imgData;
            contacts.image = [UIImage imageWithData:imageData];

            if (imgData != NULL) {
                CFRelease(imgData);
            }

            if (!contacts.image) {
                contacts.image = [UIImage imageNamed:@"avatar.png"];
            }


            //get Phone Numbers
            NSMutableArray *phoneNumbers = [[NSMutableArray alloc] init];
            ABMultiValueRef multiPhones = ABRecordCopyValue(person, kABPersonPhoneProperty);

            for(CFIndex i=0; i<ABMultiValueGetCount(multiPhones); i++) {
                @autoreleasepool {
                    CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(multiPhones, i);
                    NSString *phoneNumber = CFBridgingRelease(phoneNumberRef);
                    if (phoneNumber != nil)[phoneNumbers addObject:phoneNumber];
                    //NSLog(@"All numbers %@", phoneNumbers);
                }
            }

            if (multiPhones != NULL) {
                CFRelease(multiPhones);
            }

            [contacts setNumbers:phoneNumbers];

            //get Contact email
            NSMutableArray *contactEmails = [NSMutableArray new];
            ABMultiValueRef multiEmails = ABRecordCopyValue(person, kABPersonEmailProperty);

            for (CFIndex i=0; i<ABMultiValueGetCount(multiEmails); i++) {
                @autoreleasepool {
                    CFStringRef contactEmailRef = ABMultiValueCopyValueAtIndex(multiEmails, i);
                    NSString *contactEmail = CFBridgingRelease(contactEmailRef);
                    if (contactEmail != nil)[contactEmails addObject:contactEmail];
                    // NSLog(@"All emails are:%@", contactEmails);
                }
            }

            if (multiEmails != NULL) {
                CFRelease(multiEmails);
            }

            [contacts setEmails:contactEmails];

            [items addObject:contacts];

#ifdef DEBUG
            //NSLog(@"Person is: %@", contacts.firstNames);
            //NSLog(@"Phones are: %@", contacts.numbers);
            //NSLog(@"Email is:%@", contacts.emails);
#endif

        }
    } //autoreleasepool
    CFRelease(allPeople);
    CFRelease(addressBook);
    CFRelease(source);
    return items;

}

最近我使用CNContacts用Swift 3编写了一个pod,供需要的人使用。

Swift 联系人选择器


2
@DipakSonara 我只是举了一个例子,并不是我所有的工作代码。但它可以工作并获取我所有带有图片、电话和电子邮件的联系人。你需要创建一个仅包含一个联系人的数组,然后进行迭代。无论如何,请查看我的更新答案。 - Anton
1
我已经找到了解决方案,实际上我们需要从用户那里获取权限。 - DipakSonara
1
@DipakSonara 是的,这是正确的。与此相同的解决方案也在我的上面的代码中。ABAddressBookRequestAccessWithCompletion - Anton
5
ContactsData 是如何定义的? - Trav McKinney
4
@TravMcKinney ContactsData是我的类实例。接口ContactsData : NSObject 属性(strong, nonatomic)NSMutableArray *numbers; 属性(strong, nonatomic)NSMutableArray *emails;属性(strong, nonatomic)UIImage* image; 属性(strong, nonatomic)NSString *firstNames; 属性(strong, nonatomic)NSString *lastNames; - Anton
显示剩余9条评论

14

我没有亲自编写它,但它在我的机器上能正常工作:

ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, NULL);

if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
    ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
       ABAddressBookRef addressBook = ABAddressBookCreate( );
    });
}
else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {

    CFErrorRef *error = NULL;
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
    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));
       // NSLog(@"Name:%@ %@", firstName, lastName);

        ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
        [[UIDevice currentDevice] name];

        //NSLog(@"\n%@\n", [[UIDevice currentDevice] name]);

        for (CFIndex i = 0; i < ABMultiValueGetCount(phoneNumbers); i++) {
            NSString *phoneNumber = (__bridge_transfer NSString *) ABMultiValueCopyValueAtIndex(phoneNumbers, i);

            addressBookNum = [addressBookNum stringByAppendingFormat: @":%@",phoneNumber];
        }  
    }
    NSLog(@"AllNumber:%@",addressBookNum);
}
else {
    // Send an alert telling user to change privacy setting in settings app
}

在我的.h文件中

@property NSString * addressBookNum;

非常感谢你,伙计。 - SampathKumar
2
@SampathKumar 在我看来像个女士。 - meda
这里有很多内存泄漏,请不要忘记使用CFRelease()。总之,它能工作,并且我已经使用了这段代码(修复了泄漏)。谢谢CMD + shift + b :) - user3206558

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接