2

Introduction:

Hello, I'm currently using the AlamofireImage framework to download images in my app. I'm primarily using their ImageDownloader to download images and am using a singleton instance of this ImageDownloader to download images in a custom URLImageView I built in SwiftUI.

As far as I can tell, there doesn't seem to be a cancelAll method on the ImageDownloader class. The best there is, is a cancelRequest(with requestReceipt: RequestReceipt) method, but this requires keeping track of RequestsReceipts which is overhead I'd prefer not to manage. I've played around with this as well but it doesn't seem to cancel currently downloading images, only pending in the queue (from what I've found in testing)

Problem I'm trying to solve:

I'm running into an issue in my app where I have a few screens back to back that are VERY image heavy and display many images. When a user is on a slow cell service connection (not wifi), I see that theres a bottleneck that begins to happen where when a user goes to the next screen, it can't begin downloading the new images because its bogged down waiting for the previous screens images to complete downloading.

I'd love for a way to have a generic cancelAll method I can call that just cancels everything already pending/downloading since as I don't need previous screens to continue downloading - I need the new screen to have all the bandwidth priority to download new images.

Solutions I've Tried:

The closest I've come to replicate the behavior I want is with the following method:

func cancelAll() {

    // invalidate and cancel session
    alamofireImageDownloader.sessionManager.session.invalidateAndCancel()

    // re-init alamofire image downloader
    alamofireImageDownloader = ImageDownloader(
        configuration: ImageDownloader.defaultURLSessionConfiguration(),
        downloadPrioritization: .fifo,
        maximumActiveDownloads: 4,
        imageCache: cache
    )

}

This solution makes me nervous however because it feels weird to have to re-init the ImageDownloader every time I go to a new screen in order to cancel all pending and current image downloads.

That said this solution does work, and it allows new screens to get the full bandwidth to download images and is no longer blocked by previous screen images.

Would love some thoughts on best practice on how to do this or comments on whether my current solution is safe/smart to do.

jnpdx
  • 45,847
  • 6
  • 64
  • 94
xanderbuck
  • 221
  • 2
  • 5

0 Answers0