2

How to programmatically add a new group to the iPhone contact using AddressBook framework?

jscs
  • 63,694
  • 13
  • 151
  • 195
Mary
  • 335
  • 4
  • 14
  • 1
    Stack overflow is for specific programming questions, not a place where someone will write a program for you. – Dustin Jul 23 '12 at 12:57
  • 1
    That's a bit harsh no? Its a few lines of code not a program. – David H Jul 23 '12 at 13:00
  • thanks David your code work perfectly actaully i am a new commer in ios programming thats why i asked this type of questions. – Mary Jul 24 '12 at 12:00
  • Hello Mary will you give me your code to me I need for to my app. – Manoj Jun 17 '14 at 10:10

1 Answers1

5

First look and see if it exists, and if not, create it:

bool foundIt = NO;
// Protective - did we just not find it, or lose it?
CFArrayRef groups = ABAddressBookCopyArrayOfAllGroups(addrBook);
CFIndex numGroups = CFArrayGetCount(groups);
for(CFIndex idx=0; idx<numGroups; ++idx) {
    ABRecordRef groupItem = CFArrayGetValueAtIndex(groups, idx);

    CFStringRef name = (CFStringRef)ABRecordCopyValue(groupItem, kABGroupNameProperty);
//NSLog(@"Look at group named %@", name);
    bool isMatch = [newName isEqualToString:(NSString *)name];
    CFRelease(name);

    if(isMatch) {
        // NSLog(@"FOUND THE GROUP ALREADY!");
        groupNum = [NSNumber numberWithInt:ABRecordGetRecordID(groupItem)];
        [self setObject:groupNum forKey:kGroupID];
        foundIt = YES;
        break;
    }
}
CFRelease(groups);

if(!foundIt) {
    // lets create one
    ABRecordRef groupItem = ABGroupCreate();
    ABRecordSetValue(groupItem, kABGroupNameProperty, (CFStringRef *)newName, &error);
    if(!error) {
        ABAddressBookAddRecord (addrBook, groupItem, &error);   // bool ret = 
        ABAddressBookSave(addrBook, &error);

        groupNum = [NSNumber numberWithInt:ABRecordGetRecordID(groupItem)];
            //NSLog(@"FIRST groupNumber: %@", groupNum);
        [self setObject:groupNum forKey:kGroupID];
    }
    CFRelease(groupItem);
}
David H
  • 40,852
  • 12
  • 92
  • 138