0

我正在寻找一种方法来获取与联系人容器( CNContainer )相关的组列表( CNGroup)。当我使用谓词时,它失败了。

我正在使用的代码是

func populateGroups(tableView:NSTableView,container:CNContainer){

    print("populateGroups.start")

    print(container.name)
    print(container.identifier)

    let contactStore = CNContactStore()

    do {
        let groupsPredicate = CNGroup.predicateForGroups(withIdentifiers: [container.identifier])
        groups = try contactStore.groups(matching: groupsPredicate)
        groupNames.removeAll();
        for group:CNGroup in groups {
            self.groupNames.append(group.name)
        }
        tableView.reloadData()
    } catch {
        print( "Unexpected error fetching groups")
    }

    print("populateGroups.finish")

}

我从中得到一个错误,这对我来说没有意义。

行 groups = try contactStore.groups(matching: groupsPredicate) 导致错误。

[Accounts] 无法更新标识符为 47008233-A663-4A52-8487-9D7505847E29 的帐户,错误:Error Domain=ABAAddressBookErrorDomain Code=1002 "(null)"

这令人困惑,因为我没有更新任何帐户。

如果我将该行代码更改为 groups = try contactStore.groups(matching: nil) 我将获得所有容器的所有组。

如何创建一个谓词来返回属于 CNContactContainer 的所有 CNGroup?

4

1 回答 1

1

我通过使用 CNContainer.predicateForContainerOfGroup 检查所有组中的每个组是否属于有问题的容器来解决这个问题

func populateGroups(tableView:NSTableView,container:CNContainer){

    let contactStore = CNContactStore()

    do {
        let groups:[CNGroup] = try contactStore.groups(matching: nil)
        self.groups.removeAll();
        groupNames.removeAll();
        for group:CNGroup in groups {
            let groupContainerPredicate:NSPredicate = CNContainer.predicateForContainerOfGroup(withIdentifier: group.identifier)
            let groupContainer:[CNContainer] = try contactStore.containers(matching: groupContainerPredicate)
            if( groupContainer[0].identifier == container.identifier) {
                self.groupNames.append(group.name)
                self.groups.append(group)
            }
        }
        tableView.reloadData()

    } catch {
        print( "Unexpected error fetching groups")
    }

}
于 2017-01-30T05:26:45.477 回答