"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 CNGroup
has two properties:
So, CNGroup.identifier
this 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
), .