-2

I have about 100 GIFs in the main bundle. I'm loading everything during viewDidLoad() in an array. This array is the datasource for the UICollectionView. The problem is that these GIFs are taking a lot of memory which is causing slowness and lead to app crash due to memory. When I start scrolling, the memory debugger shows up to 800 mb+ and then crashes.

Crash

I considered integrating 3rd-party libraries to optimize the GIFs performances. Then I thought about creating some sort of local caching solution where I can offload memory and fetch data when needed in the background once the cell goes offview. Is this a right approach or am I overcomplicating things?

TyrantBoy
  • 67
  • 1
  • 6

2 Answers2

2
  1. Load gif bundle urls (only url, not image data) in viewDidLoad.
override func viewDidLoad() {
    gifUrls = ...
}
  1. Use 3rd-party view in collection view cell to display gif. For example, we use BBWebImage.
// In collection view cell
imageView = BBAnimatedImageView(frame: frame)
  1. In load gif asynchronously in collectionView(_:cellForItemAt:).
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellReuseID, for: indexPath)
    cell.tag = indexPath.item
    let url = gifUrls[indexPath.item]
    DispatchQueue.global().async {
        guard let data = try? Data(contentsOf: url) else { return }
        let gif = BBAnimatedImage(bb_data: data)
        DispatchQueue.main.async {
            guard cell.tag == indexPath.item else { return }
            cell.imageView.image = gif
        }
    }
}
Silence
  • 366
  • 1
  • 3
  • 9
1

As @rmaddy said you could load gifs in cycle of visible cells by these methods:

func collectionView(_ collectionView: UICollectionView, 
             willDisplay cell: UICollectionViewCell, 
               forItemAt indexPath: IndexPath)

More details

And:

func collectionView(_ collectionView: UICollectionView, 
        didEndDisplaying cell: UICollectionViewCell, 
               forItemAt indexPath: IndexPath)\

More details

Load gif on willDisplay and offload it on didEndDisplaying.

Arash Etemad
  • 1,827
  • 1
  • 13
  • 29
  • Currently, I'm loading the all gifs in an array at viewDidLoad. How else should I load the GIFs from the bundle? – TyrantBoy Mar 10 '19 at 07:05