Search code examples
iosobjective-caddressbookabaddressbook

Fetch Name AND Number contact list Address Book


I'm trying to NSLog name and number from my contact in Address Book. I succeed to log the name, but I don't succeed to solve the problem with number.

Here is my code :

ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
if (addressBook != NULL) {
    ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
        if (granted) {
            CFArrayRef allNames = ABAddressBookCopyArrayOfAllPeople(addressBook);

            if (allNames != NULL) {
                NSMutableArray *names = [NSMutableArray array];
                for (int i = 0; i < CFArrayGetCount(allNames); i++) {
                    ABRecordRef group = CFArrayGetValueAtIndex(allNames, i);
                    CFStringRef name = ABRecordCopyCompositeName(group);
                    [names addObject:(__bridge NSString *)name];
                    CFRelease(name);
                }


                NSLog(@"names = %@", names);
                CFRelease(allNames);
            }
        }
        CFRelease(addressBook);
    });
}

Maybe I have to create NSDictionnary ? I don't know how to solve it...


Solution

  • The phone numbers are a ABMultiValueRef:

    ABMultiValueRef phones = ABRecordCopyValue(person, kABPersonPhoneProperty);
    if (phones != NULL) {
        for (NSInteger index = 0; index < ABMultiValueGetCount(phones); index++) {
            NSString *phone = CFBridgingRelease(ABMultiValueCopyValueAtIndex(phones, index));
            NSString *label = CFBridgingRelease(ABMultiValueCopyLabelAtIndex(phones, index));  // either kABHomeLabel or kABPersonPhoneMainLabel or ...
            // do something with `phone` and `label`
        }
        CFRelease(phones);
    }