So I only recently uncovered the Contacts Framework through this video: https://youtu.be/sHKir2ZMk5Q. As such I'm not yet accustomed to the API. Basically my main problem is that I can't seem to find a way to access the name of the group a CNContact is in. The only support I can find is in Apple's own documentation, which isn't very helpful. if someone could point me in the right direction towards how to print the group name, I would be very grateful. My code is below, Cheers
// ModelData.swift
// B-Day
import Foundation
import Contacts
import SwiftUI
struct Contact: Identifiable {
let id = UUID()
let category: String
let firstName: String
let lastName: String
let birthday: DateComponents?
}
func fetchAllContacts() async -> [Contact] {
var contacts = [Contact]()
let store = CNContactStore()
let keys = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactBirthdayKey, CNContactIdentifierKey, CNGroupNameKey] as [CNKeyDescriptor]
let fetchRequest = CNContactFetchRequest (keysToFetch: keys)
do {
try store.enumerateContacts(with: fetchRequest, usingBlock: { contact, result in
//this should print the name of the contact's group
print(contact.groupName)
contacts.append(Contact(category: contact.groupName, firstName: contact.givenName, lastName: contact.familyName, birthday: contact.birthday))
})
}
catch {
print("Error")
}
return contacts
}
Fetching the group associated with a contact involves many steps as described below. Note that a contact may belong to one or more groups.
- Fetch all groups using groups(matching:) with the predicate set to nil.
- Iterate through all the fetched groups.
- Find all contacts associated with each group using predicateForContactsInGroup(withIdentifier:).
- Compare each fetched contact to the contact that you are looking for. If there is a match, then the associated group is the one that you are looking for.
- Use the name property to fetch the name of the group.