我需要阻止在我们的应用程序中显示联系人组,但是简单地从地址簿中删除组对用户来说是一种干扰。因此,我尝试在显示联系人之前删除它们,然后在完成后将它们添加回来,以便 AddressBook 保持不变,并且 iOS 联系人应用程序按原样显示组。我创建了两个数组来存储信息:
NSArray *aGroups;
NSMutableArray *aGroupMembers;
我删除组,存储它们,并在 viewWillAppear 中显示选择器:
// Remove group records for the life of this view.
CFErrorRef error;
ABAddressBookRef abRef = ABAddressBookCreate();
NSArray *groups = (NSArray *)ABAddressBookCopyArrayOfAllGroups(abRef);
if (groups.count > 0) {
// we will remove the groups so save for restoration
self.aGroups = [[NSArray alloc] initWithArray:groups];
aGroupMembers = [[NSMutableArray alloc] initWithCapacity:groups.count];
for (int i = 0; i < groups.count; i++) {
NSArray *members = (NSArray *)ABGroupCopyArrayOfAllMembers([groups objectAtIndex:i]);
NSMutableArray *memberIDs = [[NSMutableArray alloc] initWithCapacity:[members count]];
for (id member in members) {
ABRecordID ID = ABRecordGetRecordID(member);
[memberIDs addObject:[NSNumber numberWithInteger:ID]];
}
[aGroupMembers insertObject:memberIDs atIndex:i];
CFRelease(members);
[memberIDs release];
// Remove the group from the addressbook
ABAddressBookRemoveRecord(abRef, [groups objectAtIndex:i], &error);
}
CFRelease(groups);
ABAddressBookSave(abRef, nil);
self.picker.addressBook = abRef;
}
CFRelease(abRef);
然后在 viewWillDisappear 和 willResignActive 中,我“尝试”重新创建组,将成员重新添加到每个组中,然后添加回地址簿。但是,我无法将成员添加回来,因为 ABGroupAddMember() 失败。当我检查调试器中的变量时,组名和人的名字都是正确的。我看不到问题,并且 CFErrorRef 值未设置。
// Restore the group records.
if (self.aGroups != nil) {
CFErrorRef error = nil;
CFTypeRef grpName = nil;
CFTypeRef firstName = nil;
ABRecordRef newGroup = nil;
ABAddressBookRef abRef = ABAddressBookCreate();
// Re-create the groups
for (int i = 0; i < self.aGroups.count; i++) {
// Create the new group
newGroup = ABGroupCreate();
grpName = ABRecordCopyValue((ABRecordRef)[self.aGroups objectAtIndex:i], kABGroupNameProperty);
ABRecordSetValue(newGroup, kABGroupNameProperty, grpName, &error);
// Create the members
NSArray *memberIDs = (NSArray*)[aGroupMembers objectAtIndex:i];
for (NSNumber *iD in memberIDs) {
ABRecordRef person = ABAddressBookGetPersonWithRecordID(abRef,iD.intValue);
firstName = ABRecordCopyValue((ABRecordRef)person, kABPersonFirstNameProperty);
BOOL bSuccess = ABGroupAddMember(newGroup, person, &error);
if (!bSuccess) {
//NSString *errorStr = [(NSString *)CFErrorCopyDescription(error) autorelease]; // this cause EXEC_BAD_ACCESS
CFRelease(error);
}
}
CFRelease(newGroup);
CFRelease(grpName);
}
// Save the changes
ABAddressBookSave(abRef, nil);
CFRelease(abRef);
self.aGroups = nil;
[aGroupMembers removeAllObjects];
aGroupMembers = nil;
}
最佳答案
当我尝试将通过 CardDAV
协议(protocol)从 Google 同步到我的 iPhone
的联系人添加到以编程方式创建的本地群组时,就发生了这种情况。
事实证明,您无法将同步联系人添加到本地群组,反之亦然,但它只是返回 NO
,而不将 error
参数设置为任何错误消息解释为什么它不起作用。
我在我的应用程序中通过尝试将联系人添加到群组中解决了这个问题,如果它不起作用,我会通过在我的应用程序中本地保存联系人-群组关系来解决这个问题。
不太好,如果有人有办法解决这个问题,我会很高兴听到。
关于ios - 为什么 ABGroupAddMember 失败?它返回 NO 并且不设置 CFErrorRef 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13364049/