Help! Get a contact and store it in CoreData

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'.

I don't know if I get you right, but you should go through the array and because of the fetched keys you can access the needed data. then you can create new contacts from that data to store it in core data.

Help! Get a contact and store it in CoreData
 
 
Q