AsyncImage inside list is consuming a lot of memory when scrolling and eventually crash in SwiftUI

382 Views Asked by At

Here is what I have done: the app crashes when the memory goes over 1 GB or more. I tried commenting asyncImage, and it took only 25–30 MB of memory and didn't crash.

List {
            ForEach(0..<(self.imageURLArray.count), id: \.self) { i in
                AsyncImage(url: URL(string: self.imageURLArray[i])) { image in
                    image.resizable()
                        .aspectRatio(16/9, contentMode: .fit)
                        .cornerRadius(10, antialiased: true)
                        .padding(.horizontal)
                        .padding(.vertical, 5)
                }
                placeholder: {
                    ZStack {
                        RoundedRectangle(cornerRadius: 10)
                            .foregroundColor(.black.opacity(0.1))
                            .aspectRatio(16/9, contentMode: .fit)
                            .padding(.horizontal)
                            .padding(.vertical, 10)
                        ProgressView()
                            .progressViewStyle(.circular)
                    }
                }
                .onAppear {
                    if self.imageURLArray[i] == self.imageURLArray.last {
                        self.loadMoreItems()
                    }
                }
            }
            .listRowInsets(EdgeInsets())
        }
1

There are 1 best solutions below

0
On

I just put asyncImage inside a LazyVStack and now it only consumes memory for the images that are visible.

List {
        ForEach(0..<(self.imageURLArray.count), id: \.self) { i in
            LazyVStack {
                AsyncImage(url: URL(string: self.imageURLArray[i])) { image in
                    image.resizable()
                        .aspectRatio(16/9, contentMode: .fit)
                        .cornerRadius(10, antialiased: true)
                        .padding(.horizontal)
                        .padding(.vertical, 5)
                }
                placeholder: {
                    ZStack {
                        RoundedRectangle(cornerRadius: 10)
                            .foregroundColor(.black.opacity(0.1))
                            .aspectRatio(16/9, contentMode: .fit)
                            .padding(.horizontal)
                            .padding(.vertical, 10)
                        ProgressView()
                            .progressViewStyle(.circular)
                    }
                }
                .onAppear {
                    if self.imageURLArray[i] == self.imageURLArray.last {
                        self.loadMoreItems()
                    }
                }
            }
        }
        .listRowInsets(EdgeInsets())
    }