【问题标题】:How to get an array of CNGroup from a CNContainer using CNContactStore?如何使用 CNContactStore 从 CNContainer 中获取 CNGroup 数组?
【发布时间】:2017-06-15 03:06:14
【问题描述】:

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

我使用的代码是

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=ABAddressBookErrorDomain Code=1002 "(null)"

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

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

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

【问题讨论】:

    标签: swift macos cncontactstore


    【解决方案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")
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多