Display an image from CoreData in SwiftUI

Viewed 890

I have managed to save an image to CoreData using the following code:

let imageData = try Data(contentsOf: fileURL!)
let img = UIImage(data: imageData)
student.picture = img?.pngData()

Of course, picture is of type Data.

Now, I would like to display this image in SwiftUI.

struct StudentView: View {
  @Environment(\.managedObjectContext) var managedObjectContext
  @ObservedObject var student: Student

  var body: some View {
    VStack {
      Image(...student.picture...)
      Text("\(student.lastName)")   
    }
  }
}

But I cannot figure out what to put in place of ...student.picture....

Thanks for your help.

1 Answers

If I correctly understood your model then the following should work

Image(uiImage: UIImage(data: student.picture ?? Data()) ?? UIImage())
Related