Load images async in SwiftUI with DispatchQueue

Viewed 1960

I created a home view with three navigationlinks. With a click, a view appears with a List of 180 images, fetched from AWS S3. During scrolling, the view is hitching. Therefore the images shall load in background async. I already implemented a downsample-function for reducing the memory footprint. I followed the talk from WWDC 2018, which explains how to implement async loading using DispatchQueue. But I don't get it to work. BTW, I'm pretty new to SwiftUI and Swift.

I tried to implement it like in this screenshot from the WWDC talk. My implementation is commented in my own code snippet below. Screenshot I also tried to work with the Combine framework, but didn't find a solution for my problem. Most websites describe how to work with DispatchQueue in Swift, but not in SwiftUI, what makes it difficult for me where to start off.

var body: some View {
        List {
            ForEach(range.count, id: \.self) { item in
                NavigationLink(destination: ImageLargeView()) {
                    //DispatchQueue.main.async {
                    Image(uiImage: downsample(thisReturnesAllDownsampledImagesAsUIImage))
                    //}
                }
                .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: 200, alignment: .center)
                .clipped()
            }
        }
}

My aim is to get rid of the hitching behaviour with a minimum of memory footprint.

1 Answers

Take a look at some blog posts about asynchronous image loading in SwiftUI. This one for instance looks like it describes the technique you need to use perfectly.

In a nutshell: put a custom View in your hierarchy that handles downloading on a background thread and then updates the image when the view has been downloaded.

There are Cocoapods available as well, like this one for instance.

Related