I'm currently trying to save a selected image in core data as a type data, but I'm getting an error in the persistence file marked with a comment. I've included my code and any questions I will gladly answer. Thanks for any help!
Content View:
import SwiftUI
import PhotosUI
struct ContentView: View {
@ObservedObject var persistence = PersistenceController.shared
@State var selectedItems: [PhotosPickerItem] = []
@State var data: Data?
var body: some View {
NavigationView{
VStack{
Spacer()
VStack{
Spacer()
if let data = data, let uiimage = UIImage(data: data) {
Image(uiImage: uiimage)
.resizable()
.scaledToFit()
.frame(width: 250, height: 500)
}
Spacer()
}
Spacer()
PhotosPicker(selection: $selectedItems, maxSelectionCount: 1, matching: .images){
Text("Pick Photo")
}
.onChange(of: selectedItems){ newValue in
guard let item = selectedItems.first else{
return
}
item.loadTransferable(type: Data.self){ result in
switch result {
case .success(let data):
if let data = data{
self.data = data
} else {
print("Data is nil")
}
case .failure(let failure):
fatalError("\(failure)")
}
}
}
Spacer()
}
.navigationBarItems(trailing: addButton)
}
}
var addButton: some View {
Button(action: {
guard let item = selectedItems.first else{
return
}
item.loadTransferable(type: Data.self){ result in
switch result {
case .success(let data):
if let data = data{
persistence.addObject(image: data)
} else {
print("Data is nil")
}
case .failure(let failure):
fatalError("\(failure)")
}
}
}){
Text("Add Image").bold()
}
}
}
Persistence:
import Foundation
import CoreData
class PersistenceController: ObservableObject {
static let shared = PersistenceController()
let container: NSPersistentContainer
init(inMemory: Bool = false) {
container = NSPersistentContainer(name: "ReciPlanner")
if inMemory {
container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
}
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
container.viewContext.automaticallyMergesChangesFromParent = true
}
func addObject(image: Data){
let context = container.viewContext
let object = Object(context: context) //Error: Thread 7: "An NSManagedObject of class 'Object' must have a valid NSEntityDescription."
object.item = image
}
func contextSave() {
let context = container.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
print("**** ERROR: Unable to save context \(error)")
}
}
}
}
Data Model: