Search code examples
imageswiftuinsdataimage-conversion

Coredata Image conversion swiftUI


I'm building a simple CoreData app. At one point the user is able to upload and store an image with CoreData in the NSData format. Saving the managedobjectcontext works like follows:

    let item = Item(context: self.managedObjectContext)

    item.theImage = selectedImageFromPicker.pngData() as NSData?

    //saving the MOC

Now, when im trying to retrieve the image im facing a series of issues.

    struct Box {

      var id: Int

      let title: String

      let image: NSData?

    }



    struct BoxView: View {

      let box: Box

      let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

      var item: Item


      var body: some View {

        VStack {


        Image(uiImage: UIImage(data: box.image) as! Data)

        .resizable()
            .frame(width: 120, height: 120, alignment: .center)
            .aspectRatio(contentMode: .fill)

      }

      }

    }

I'm pretty sure displaying the Image() with a UIImage that contains data is faulty here, but I cant figure out how to convert the data to a format that is displayed by the Image() method. Unfortunately Xcode won't help with its error messages either and rather blames it on the VStack.

Maybe someone else was in the situation before and could help because I didn't find anything online to this specific issue.


Solution

  • As far as I understood you need something like the following (I removed non-related to image code for shortness and simplicity)

    var body: some View {
        VStack {
            image
        }
    }
    
    var image: some View {
        if let nsData = box.image, let uiImage = UIImage(data: nsData as Data) {
            return AnyView(Image(uiImage: uiImage)
                .resizable()
                .frame(width: 120, height: 120, alignment: .center)
                .aspectRatio(contentMode: .fill))
            }
        return AnyView(EmptyView())
    }