First check if the group exists:
-(void) CheckIfGroupExistWithName:(NSString*)groupName { BOOL hasGroup = NO; //checks to see if the group is created ad creats group for HiBye contacts ABAddressBookRef addressBook = ABAddressBookCreate(); CFIndex groupCount = ABAddressBookGetGroupCount(addressBook); CFArrayRef groupLists= ABAddressBookCopyArrayOfAllGroups(addressBook); for (int i=0; i<groupCount; i++) { ABRecordRef currentCheckedGroup = CFArrayGetValueAtIndex(groupLists, i); NSString *currentGroupName = (NSString *)ABRecordCopyCompositeName(currentCheckedGroup); if ([currentGroupName isEqualToString:groupName]){ //!!! important - save groupID for later use self.groupId = ABRecordGetRecordID(currentCheckedGroup); hasGroup=YES; } [groupName release]; } if (hasGroup==NO){ //id the group does not exist you can create one [self createNewGroup:groupName]; } //CFRelease(currentCheckedGroup); CFRelease(groupLists); CFRelease(addressBook);
}
Use this to create a new group and save its identifier.
-(void) createNewGroup:(NSString*)groupName { ABAddressBookRef addressBook = ABAddressBookCreate(); ABRecordRef newGroup = ABGroupCreate(); ABRecordSetValue(HiByeGroup, kABGroupNameProperty,groupName, nil); ABAddressBookAddRecord(addressBook, newGroup, nil); ABAddressBookSave(addressBook, nil); CFRelease(addressBook);
}
How to establish contact with the group
//Use the Group ID you stored. ABRecordRef HiByeGroup = ABAddressBookGetGroupWithRecordID(addressbook, self.groupId); BOOL didAdd = ABGroupAddMember(HiByeGroup,ref,&error); if (!didAdd) { // Update to handle the error appropriately. NSLog(@"Unresolved error while adding person to HiBye group %@", &error); exit(-1); // Fail } BOOL didSave = ABAddressBookSave(addressbook, &error); if (!didSave) { // Update to handle the error appropriately. NSLog(@"Unresolved error while saving address book%@", &error); exit(-1); // Fail }
Good luck.
source share