SwiftData is the new framework for persistent data storage in SwiftUI. If you tried it and wanted to save an Image, you might have encountered this error:
No exact matches in call to instance method ‚getValue‘
The problem is that SwiftData can’t save objects of the type Image. That’s because you shouldn’t save an Image as it’s a View and not some object only storing the data of the image. It also stores any modifiers etc. that you applied to it.
You should have your image as an UIImage. Usually you have that already. Either you created your image from one with the
Image(uiImage: myImage)
Initialiser or have the image in your asset catalogue and can create an UIImage from.
UIImage(named: "MyImage")
If you try to save your UIImage in SwiftData now you notice that it gives the same error message.
To save our image we need to convert it to a Data object and save this.
To do that we use the .pngData() method of UIImage. It gives us a Data object that we can now save in SwiftData.
@Model class MyClass {
var imageData: Data
init(imageData: myImageData) {
self.imageData = imageData
}
}
To reverse the process and get an UIImage or an Image back from our Data object we initialise a new UIImage with our Data and if we need to we initialise an Image with the newly created UIImage.
let myUIImage = UIImage(data: myImageData)
let myImage = Image(uiImage: myUIImage)
Now you know how to save and get back your images in SwiftData.
