Finding contacts through a group using CNContact

Using Swift2, I try to find all the contacts that are members of the Work group, and simply return them.

After creating the predicate.

let workPred = CNContact.predicateForContactsInGroupWithIdentifier("Work")
let keysToFetch = [CNContactGivenNameKey]
let results = contacts.unifiedContactsMatchingPredicate(workPred, keysToFetch)

However, it always returns 0 results when there are group id contacts.

+4
source share
1 answer

"Work"not a group identifier. You should receive groups through CNContactStore groupsMatchingPredicate:

  • func groupsMatchingPredicate(_ predicate: NSPredicate?) throws -> [CNGroup]

Then you will get an array of objects CNGroup. Each CNGrouphas two properties:

  • name and
  • identifier.

So, CNGroup.identifierthis is what you want to use in your predicate. Example objects CNGroup:

[
  <CNGroup: 0x7fe563ca91f0: identifier=2DFE28EB-A9CA-4920-A77D-46BEE5A09E96, name=Friends>,
  <CNGroup: 0x7fe563ca3bc0: identifier=E007B6DD-F456-48FA-A564-32256A898B67, name=Work>
]

Here you can see that the identifier is generated by the UUID. Not the name of the group.

:

do {
  let store = CNContactStore()

  let groups = try store.groupsMatchingPredicate(nil)
  let filteredGroups = groups.filter { $0.name == "Work" }

  guard let workGroup = filteredGroups.first else {
    print("No Work group")
    return
  }

  let predicate = CNContact.predicateForContactsInGroupWithIdentifier(workGroup.identifier)
  let keysToFetch = [CNContactGivenNameKey]
  let contacts = try store.unifiedContactsMatchingPredicate(predicate, keysToFetch: keysToFetch)

  print(contacts)
}
catch {
  print("Handle error")
}

( CNGroup), .

+8

Source: https://habr.com/ru/post/1610613/


All Articles