I am a beginner in SwiftUI and am trying to load and display multiple images horizontally at once. When I debug, it looks like the platformLogos exists and the ForEach loop is running, but nothing appears on the screen. The .border(.blue) is not appearing either.
Any suggestion will be helpful. Thank you!
import UIKit
class ImageLoader: ObservableObject {
private static let imageCache = NSCache<AnyObject, AnyObject>()
@Published var image: UIImage? = nil
@Published var images: [UIImage]? = nil
public func downloadImage(url: URL) {
let urlString = url.absoluteString
if let imageFromCache = ImageLoader.imageCache.object(forKey: urlString as AnyObject) as? UIImage {
self.image = imageFromCache
return
}
URLSession.shared.dataTask(with: url) { (data, res, error) in
guard let data = data, let image = UIImage(data: data) else {
return
}
DispatchQueue.main.async { [weak self] in
ImageLoader.imageCache.setObject(image, forKey: urlString as AnyObject)
self?.image = image
}
}.resume()
}
public func downloadImages(urls: [URL]) {
for url in urls {
let urlString = url.absoluteString
if let imageFromCache = ImageLoader.imageCache.object(forKey: urlString as AnyObject) as? UIImage {
self.images?.append(imageFromCache)
return
}
URLSession.shared.dataTask(with: url) { (data, res, error) in
guard let data = data, let image = UIImage(data: data) else {
return
}
DispatchQueue.main.async { [weak self] in
ImageLoader.imageCache.setObject(image, forKey: urlString as AnyObject)
self?.images?.append(image)
}
}.resume()
}
}
}
@ObservedObject var logoLoader: ImageLoader = ImageLoader()
@ObservedObject var gameDetail: GameDetail = GameDetail()
var body: some View {
VStack (alignment: .leading) {
platformLogoView(platformLogos: self.logoLoader.images)
.onAppear {
if let logoURLs = self.gameDetail.game?.platformLogosUrls {
self.logoLoader.downloadImages(urls: logoURLs)
}
}
}
}
struct platformLogoView: View {
var platformLogos: [UIImage]?
let rows = [GridItem(.fixed(30)), GridItem(.fixed(30))]
var body: some View {
Grid {
ForEach(platformLogos ?? [UIImage](), id: \.self ) { logo in
GridRow {
Image(uiImage: logo)
.resizable(resizingMode: Image.ResizingMode.stretch)
.aspectRatio(contentMode: .fit)
.clipped()
}
Divider()
}
}
.border(.blue)
}
}
I created the downloadImages function and simply followed the same logic as the singular downloadImage function, but appending the loaded image to an array. I was thinking of using lazyHGrid instead of Grid but neither of them worked. I am simply not seeing anything on screen.




