Using Swift2 I am trying to find all contacts that are members of the "Work" group and just return those contacts.
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 contacts of the group id.
"Work"
is not group identifier. You have to fetch groups via CNContactStore
's groupsMatchingPredicate
:
func groupsMatchingPredicate(_ predicate: NSPredicate?) throws -> [CNGroup]
Then you'll get an array of CNGroup
objects. Every CNGroup
has two properties:
name
andidentifier
.So CNGroup.identifier
is what you want to use in your predicate. An example of CNGroup
objects:
[
<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 UUID. Not the group name.
Here's an example:
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")
}
Didn't find any suitable predicate (on CNGroup
) to match group name directly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With