1

How can I get all group names that is saved inside the contacts? Below is my code for your reference:

NSMutableArray *list = [NSMutableArray array];
ABAddressBookRef myAddressBook = ABAddressBookCreate();
CFArrayRef allSources = ABAddressBookCopyArrayOfAllGroups(myAddressBook);

list = [NSMutableArray arrayWithArray: (__bridge NSArray*) allSources];

NSLog(@"GROUPS %@",[list objectAtIndex:0]);

The NSLog returns a but I need to get the group name itself.

Thanks.

jettplaine
  • 45
  • 1
  • 6

2 Answers2

2

Use the ABRecordCopyCompositeName() function.

ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
if (addressBook != NULL) {
    ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
        if (granted) {
            CFArrayRef allGroups = ABAddressBookCopyArrayOfAllGroups(addressBook);
            if (allGroups != NULL) {
                NSMutableArray *names = [NSMutableArray array];
                for (int i = 0; i < CFArrayGetCount(allGroups); i++) {
                    ABRecordRef group = CFArrayGetValueAtIndex(allGroups, i);
                    CFStringRef name = ABRecordCopyCompositeName(group);
                    [names addObject:(__bridge NSString *)name];
                    CFRelease(name);
                }
                NSLog(@"names = %@", names);
                CFRelease(allGroups);
            }
        }
        CFRelease(addressBook);
    });
}
Carl Veazey
  • 18,392
  • 8
  • 66
  • 81
  • Your code did not work out of the box but after a little editing it did the trick. Thanks Carl! – jettplaine Aug 11 '13 at 07:43
  • You're welcome, sorry it didn't work right for you immediately. I assure you I tested it on an iPhone 5 running iOS 6.1 and observed that it logged the correct output. Glad you were able to fit it to your purposes! – Carl Veazey Aug 11 '13 at 07:46
  • Hello, I tried this code and the method ABAddressBookCopyArrayOfAllGroups return 0 objects despite I have two groups in my iPhone "Gmail" and "On my iPhone". – Vervatovskis Feb 04 '15 at 13:31
  • @Vervatovskis: Sounds like you might have a permissions issue. Use the `ABAddressBookGetAuthorizationStatus` to check your status. And use `ABAddressBookRequestAccessWithCompletion` to request access if needed. – Rickster Jul 17 '15 at 00:51
0

This works for me:

ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, nil);

NSArray *allGroups = CFBridgingRelease(ABAddressBookCopyArrayOfAllGroups(addressBook));
NSInteger numberOfGroups = [allGroups count];

for (NSInteger i = 0; i < numberOfGroups; i++) {
    ABRecordRef group = (__bridge ABRecordRef)allGroups[i];

    NSString *groupName = CFBridgingRelease(ABRecordCopyCompositeName(group));
    NSLog(@"group = %@",groupName);

    NSLog(@"=============================================");
}
Rickster
  • 870
  • 10
  • 17