0

I have a CoreData Entity “GameSession” with an attribute “photo” which is of type “Binary Data” (and I clicked on “Allows External Storage”).

In a view, I save a photo in that attribute, like that:

PhotosPicker(selection: $selectedItem ,matching: .images) {
    Label("Select a photo", systemImage: "photo")
}
.onChange(of: selectedItem) { newItem in
    Task {
        if let data = try? await newItem?.loadTransferable(type: Data.self) {
            selectedPhotoData = data
        }
    }
}

Then I save it in my CoreData Entity “GameSession” in the attribute “photo” which is of type “Binary Data”, like that

let newSession = GameSession(context: self.moc)
        newSession.date = self.date
        newSession.setValue(self.selectedPhotoData, forKeyPath: "photo")
self.moc.save()

Everything works fine but I am wondering if I am not going to hit a memory issue when I will have a high number of “session” (and so a high number of photo).

Moreover, In my application, I only display the photo in a small square of 300 pixel by 300 pixels. So I don’t really need to store it in my coredata entity in high resolution.

How could I reduce the size of the photo BEFORE saving it? I guess I have to apply a “reduce_size” function to “selectedItem” or “newItem” in my PhotosPicker, but I don’t know how.

I know there is UIImageJPEGRepresentation that I could use and apply a compression ratio, But how to use that method on $selectedItem ?

Thanks and regards

  • Consider to save the image(s) on disk and keep only the path in Core Data. – vadian Dec 24 '22 at 14:39
  • Hi @vadian and thanks for the answer. I read a lot about saving only the path in coredata, but it looks like for small images, saving images in binary data should work very well. That’s why I am trying to reduce their size before saving. Would you k ow how to do it? – user20587286 Dec 24 '22 at 16:52

0 Answers0