问题
i want to delete the group on addressBook. i have try this code it is successfully delete the group but on main addressBook contact are not deleted.
CFErrorRef error = NULL;
ABAddressBookRef iPhoneAddressBook = ABAddressBookCreate();
ABRecordRef newGroup;
newGroup = ABAddressBookGetGroupWithRecordID(iPhoneAddressBook,groupId);
ABAddressBookRemoveRecord(iPhoneAddressBook, newGroup, &error);
ABAddressBookSave(iPhoneAddressBook,&error);
my requirement is i have one service to call every time when application is open i have get contact from service in a specific group. so i have delete old group and add new contact which is provide from service but it will twice the contact on main AddressBook because it will only delete group. i want to delete group as well as this group contact are delete on main addressBook both.
Finally my question is... How can i delete the group and group contact from main AddressBook please help me... Thank you in advance..
回答1:
You can Do this
-(void)RemoveContactGroup:(NSString *)name {
BOOL flag = [self CheckIfGroupExistWithName:name];
if(!flag)
{
return;
}
CFErrorRef error = NULL;
ABAddressBookRef iPhoneAddressBook = ABAddressBookCreate();
ABRecordRef newGroup;
//if Existing Group
newGroup = ABAddressBookGetGroupWithRecordID(iPhoneAddressBook,groupId);
NSArray *member = (__bridge NSArray *)ABGroupCopyArrayOfAllMembers(newGroup);
int nPeople = (int)[member count];
if (nPeople>0)
{
for (int i=0; i<nPeople; i++)
{
ABRecordRef contactPerson = (__bridge ABRecordRef)member[i];
ABAddressBookRemoveRecord(iPhoneAddressBook, (ABRecordRef)contactPerson, &error);
}
}
ABAddressBookSave(iPhoneAddressBook, NULL);
CFRelease(newGroup);
}
First you can check the group are exist or not if exist give the group id
-(BOOL)CheckIfGroupExistWithName:(NSString*)groupName {
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 = (__bridge NSString *)ABRecordCopyCompositeName(currentCheckedGroup);
if ([currentGroupName isEqualToString:groupName]){
//!!! important - save groupID for later use
groupId = ABRecordGetRecordID(currentCheckedGroup);
hasGroup=YES;
}
CFRelease(currentCheckedGroup);
}
if (hasGroup==NO){
//id the group does not exist you can create one
}
return hasGroup;
}
Check It.
来源:https://stackoverflow.com/questions/35569682/how-can-i-delete-contact-from-main-addressbook-when-i-delete-specific-group-in-o