Asynchronously Loading Photo into Table and Collection Views

Emmanuel Orvain
2 min readSep 23, 2021

--

This operation is critical for user experience and for the stability of an iOS application. A huge amount of application are facing this issue. I read some resources or snippet that answer to this question, but I found that they were breaking some rules that are important to me.

What is important to me :

  • Scrolling must be smooth
  • The cell views must not update themselves from the model objects
  • The download of image must be testable (No dependency to UIView lifecycle)
  • The class in charge of the download of image must not update the cell views
  • Use the recycle cell view provided by UIKit
  • Use a cache policy

Create an adapter for each reusable cell

The datasource has the responsibility to :

  • Launch the download requests
  • Associate each reusable view with each reusable adapter
  • Update the cell views (activity, image, …)

This system will ensure, that we keep the association between reusable cell on their download tasks. One cell has one adapter, and it is managed by the datasource.

Thanks to this we respects these goals :

  • The cell views must not update themselves from the model objects
  • The class in charge of the download of image must not update the cell views
  • Use the recycle cell view provided by UIKit

Load an image from URL

The reusable adapter has the following responsibilities :

  • Definition of the URLSession cache policy
  • Cancel the previous data task when a reusable cell is associated with a new row
  • Don’t feed the list view controller, if the cell is associated to a new row, but is still not cancelled by the session.
  • Manage the UI Thread, and the network thread
  • Manage the network error

If you really want to be independent of UIKit, then return Data? type in the completion handler.

If you enjoyed this post, please leave some claps. 👏👏👏

You can clap up to 50 times, so get clicking/tapping! 😉

--

--

Emmanuel Orvain
Emmanuel Orvain

Written by Emmanuel Orvain

French iOS / Android experimented developper from Toulouse in south of France. https://occirama.com/scanandfile/

No responses yet