I want to display an image (type UIImage) which is stored in an EnvironmentObject. This EnvironmentObject consists of an array of a structure which holds an UIImage element. In a view, I want to display an image of this array but this doesn't work somehow.
Here's the struct:
struct TestStruct: Identifiable {
var id: String
var name: String
var image: UIImage
init() {
id = ""
name = ""
image = UIImage.init()
}
}
Here the ModelData class:
final class ModelData: ObservableObject {
@Published var testStruct: [TestStruct] = []
}
And this is the instantiation of modelData in the main app code:
struct TestApp: App {
@ObservedObject private var modelData = ModelData()
init() {...
The content of the modelData is loaded from a Firebase database and Firebase storage. This actually works, I can see the downloaded images in the modelData.testStruct[...].image in the debug preview.
From a view, I want to reference the image from the modelData:
struct StructContentView: View {
@EnvironmentObject var modelData: ModelData
var body: some View {
ScrollView {
Image(uiImage: modelData.testStruct[0].image)
.frame(width: 64.0, height: 64.0)
.foregroundColor(.red)
}
}
}
Can someone help me? I'm generally confused with ObservableObject/EnvironmentObject and that stuff but I was able to display e.g. the field "name" of modelData.testStruct[0] in a TextView. Is the passing of the UIImage to the Image view wrong, maybe? Or something else needed there?
Thanks in advance for your support.
CodePudding user response:
In the getData completion callback of Firestone, it's set:
let reference = Storage.storage().reference(forURL: tempStruct.imageUrl)
reference.getData(maxSize: (1 * 1024 * 1024)) { (data, error) in
if let _error = error{
print(_error)
} else {
if let _data = data {
tempStruct.image = UIImage(data: _data)!
}
}
}
...
modelData.testStruct.append(tempStruct)
This is done when the App is started. The image will/shall then be later shown when the user goes to another menu item.
Solution:
The image of the testStruct type had to be changed to @Published, therefore it was also needed to change testStruct to a class:
class TestStruct: ObservableObject {
var id: String
var name: String
@Published var image: UIImage
init() {
id = ""
name = ""
image = UIImage.init()
}
}