Search code examples
iosswiftgifgiphygiphy-api

displaying a lot of gifs in collectionview


In my app I want to show gifs from giphy. The fetching and everyting is no problem, but I don't know what's the best way to display for example all trending gifs. I have a collectionview which should display all gifs with this code:

  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: GifChooserCell.cellIdentifier, for: indexPath) as! GifChooserCell

      let data = try! Data(contentsOf: gif.giphyURL)
      let image = FLAnimatedImage(animatedGIFData: data)
      cell.image.animatedImage = image


    return cell
  }

The problem is that this loads everything into RAM and the application is extremely slow. What's the best way to do this? Async? Lazy loading?


Solution

  • I encountered the same issue with AImage which also loads APNG files. What I found was that all these Gif and APNG frameworks use separate CADisplayLinks for their firing. In my case, CPU usage was about 7% per cell, and grew linearly with the # of cells.

    When I disabled the CADisplayLinks objects, my CPU usage was about 3% total after loading.

    For a solution, I'm considering stopping all animation once scrolling starts, or possibly using a singleton to drive all my APNG files.

    Hope this helps.


    UPDATE:

    I went ahead and converted all my APNG files to MSSticker items by first saving the APNG files to disk, and then creating an array of stickers.

    Using Stickers, my CPU usage is at 5% and memory is at 60MB for 7 APNG files. My original method of using an AImageView to drive each APNG gets about 40% CPU usage.