overview of the problem
I'm making an app with SwiftUI.
We even implemented fetching contacts using CNContactStore.
The goal is to get the contacts and store them separately in CoreData.
This is because you need to assign and manage attributes that are not in the default contact.
class ContactStore: ObservableObject {
@Environment(\.managedObjectContext) private var viewContext
@Published var error: Error? = nil
@Published var results: [CNContact] = []
func fetch() {
do {
let store = CNContactStore()
let keysToFetch = [CNContactGivenNameKey as CNKeyDescriptor,
CNContactMiddleNameKey as CNKeyDescriptor,
CNContactFamilyNameKey as CNKeyDescriptor,
CNContactImageDataAvailableKey as CNKeyDescriptor,
CNContactPhoneNumbersKey as CNKeyDescriptor,
CNContactImageDataKey as CNKeyDescriptor]
os_log("Fetching contacts: now")
let containerId = store.defaultContainerIdentifier()
let predicate = CNContact.predicateForContactsInContainer(withIdentifier: containerId)
let contacts = try store.unifiedContacts(matching: predicate, keysToFetch: keysToFetch)
os_log("Fetching contacts: succesfull with count = %d", contacts.count)
self.results = contacts
print(results)
} catch let error {
print("error occured! : \(error.localizedDescription)")
}
}
}
problem
Is there a way to store the contact information in the array 'results' as CoreData?
The attributes set in CoreData are 'name', 'phone', and 'company'.