首页 > 解决方案 > 在 iPad 设备中创建/删除地址簿组失败

问题描述

我正在尝试通过创建一个组来管理我的应用程序的联系人。

创建/删除组在模拟器上运行良好(使用 iOS 11.3 和 iOS 9.3)。

在这两种情况下,iOS 设置中的默认联系人设置都设置为 iCloud。

我在这两种情况下都检查了隐私设置,访问设备联系人的权限设置为YES

以下代码在装有 iOS 9.3.5 的 iPad 上失败。

-(void) createNewGroup:(NSString*)groupName
{
    CFErrorRef error = NULL;
    ABAddressBookRef ab = ABAddressBookCreateWithOptions(NULL, &error);
    if (ab) {
        ABRecordRef newGroup = ABGroupCreate();
        ABRecordSetValue(newGroup, kABGroupNameProperty,(__bridge CFTypeRef)(groupName), nil);
        ABAddressBookAddRecord(ab, newGroup, &error);

        if (error) {
             DDLogDebug(@"cannot create group -%@",error);
        }else{
            ABAddressBookSave(ab, &error);
        }

        if (error) {
           DDLogDebug(@"cannot save group -%@",error);
        }
        //!!! important - save groupID for later use
        self.groupId = ABRecordGetRecordID(newGroup);  //-1 for iPad, and for other cases 2,3,4 ....
        DDLogDebug(@"createNewGroup : %i",self.groupId );

        CFRelease(newGroup);
        CFRelease(ab);
    }
}

并删除组:

注意:我没有在 iPad 上测试这个方法,因为没有我想删除的组,我会在我能够在 iPad 上创建一个组后测试这个。此方法在模拟器上按预期工作。

-(BOOL)deleteGroup:(NSString *)groupName{

    BOOL res;
    CFErrorRef error;
    ABAddressBookRef ab = ABAddressBookCreate();

    NSArray *groups = (__bridge NSArray *) ABAddressBookCopyArrayOfAllGroups(ab);

    for (id _group in groups)
    {
        NSString *currentGroupName = (__bridge NSString*) ABRecordCopyValue((__bridge ABRecordRef)(_group), kABGroupNameProperty);
        DDLogDebug(@"group name -%@",currentGroupName);
        if ([groupName isEqualToString:currentGroupName])
        {
            res = ABAddressBookRemoveRecord(ab, (__bridge ABRecordRef)(_group), &error);
            return res;
        }

    }

    return NO;
}

我没有收到任何错误,但尝试在 iPad 上创建组时,我将 groupID 设为 -1,并且我检查该组根本没有创建。

标签: iosobjective-cabaddressbook

解决方案


推荐阅读