I am new to SwiftUI and also Combine. I have a simple List and I am loading iTunes data and building the list. Loading of the images works - but they are flickering, because it seems my dispatch on the main thread keeps firing. I am not sure why. Below is the code for the image loading, followed by where it's implemented.
struct ImageView: View {
@ObservedObject var imageLoader: ImageLoaderNew
@State var image: UIImage = UIImage()
init(withURL url: String) {
imageLoader = ImageLoaderNew(urlString: url)
}
func imageFromData(_ data: Data) -> UIImage {
UIImage(data: data) ?? UIImage()
}
var body: some View {
VStack {
Image(uiImage: imageLoader.dataIsValid ?
imageFromData(imageLoader.data!) : UIImage())
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width:60, height:60)
.background(Color.gray)
}
}
}
class ImageLoaderNew: ObservableObject
{
@Published var dataIsValid = false
var data: Data?
// The dispatch fires over and over again. No idea why yet
// this causes flickering of the images in the List.
// I am only loading a total of 3 items.
init(urlString: String) {
guard let url = URL(string: urlString) else { return }
let task = URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data else { return }
DispatchQueue.main.async {
self.dataIsValid = true
self.data = data
print(response?.url as Any) // prints over and over again.
}
}
task.resume()
}
}
And here it's implemented after loading the JSON, etc.
List(results, id: \.trackId) { item in
HStack {
// All of these image end up flickering
// every few seconds or so.
ImageView(withURL: item.artworkUrl60)
.padding(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 5))
VStack(alignment: .leading) {
Text(item.trackName)
.foregroundColor(.gray)
.font(.headline)
.truncationMode(.middle)
.lineLimit(2)
Text(item.collectionName)
.foregroundColor(.gray)
.font(.caption)
.truncationMode(.middle).lineLimit(1)
}
}
}
.frame(height: 200.0)
.onAppear(perform: loadData) // Only happens once
I am not sure why the images keep loading over and over again (yet). I must be missing something simple, but I am definitely not wise to the ways of Combine quite yet. Any insight or solution would be much appreciated.
