iphoneobjective-ciosabaddressbookaddressbookui

How to get all phone numbers with labels for all contacts in address book?


I want to get all the phone numbers with diff labels like "iPhone", "home phone", "mobile number", "other numbers" , etc. for a contact stored in iPhone address book.

How do I get it?

Please help.

Thanks in advance.

I am trying: which is crashing

ABAddressBookRef ab=ABAddressBookCreate();

    CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(ab);
    NSMutableArray *allNumbers = [[NSMutableArray alloc] initWithCapacity:CFArrayGetCount(people)];

    for (CFIndex i = 0; i < CFArrayGetCount(people); i++) {
        ABRecordRef person = CFArrayGetValueAtIndex(people, i);
        ABMultiValueRef numbers = ABRecordCopyValue(person, kABPersonPhoneProperty);

        for (CFIndex j=0; j < ABMultiValueGetCount(numbers); j++) {


            CFStringRef locLabel = ABMultiValueCopyLabelAtIndex(numbers, i);
            NSString *phoneLabel =(NSString*) ABAddressBookCopyLocalizedLabel(locLabel);

            CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(numbers, j);
            CFStringRef locLabel1 = ABMultiValueCopyLabelAtIndex(numbers, j);
            NSString *phoneLabel1 =(NSString*) ABAddressBookCopyLocalizedLabel(locLabel);

             NSLog(@" ####### phone no -> %@ , phone label -> %@  #######)", locLabel1, phoneLabel1);
            //CFRelease(phones);
            NSString *phoneNumber = (NSString *)phoneNumberRef;
            CFRelease(phoneNumberRef);
            CFRelease(locLabel);
            NSLog(@"phone no -> %@ , phone label -> %@)", phoneNumber, phoneLabel);
            [phoneNumber release];
        }
        CFRelease(numbers);
    }

    CFRelease(people);

Solution

  • Solved it this way:

      ABAddressBookRef addressBook = ABAddressBookCreate();
    CFArrayRef all = ABAddressBookCopyArrayOfAllPeople(addressBook);
    CFIndex n = ABAddressBookGetPersonCount(addressBook);
    
    for( int i = 0 ; i < n ; i++ )
    {
        ABRecordRef ref = CFArrayGetValueAtIndex(all, i);
        NSString *firstName = (NSString *)ABRecordCopyValue(ref, kABPersonFirstNameProperty);
        NSLog(@"Name %@", firstName);
    
        ABMultiValueRef phones = ABRecordCopyValue(ref, kABPersonPhoneProperty);
        for(CFIndex j = 0; j < ABMultiValueGetCount(phones); j++)
        {
    
            CFStringRef locLabel1 = ABMultiValueCopyLabelAtIndex(phones, j);
            NSString *phoneLabel1 =(NSString*) ABAddressBookCopyLocalizedLabel(locLabel1);
    
              NSLog(@"  ### %@  --- %@ ### )", locLabel1, phoneLabel1);
    
        }
    }