https://github.com/Sylvia-YiyinShen/MultiImageDownload
This guide is only for learning purpose, and the demo just simulates what AlamofireImage does. Keys to implement multi image downloading task in this demo.
Image caching strategy
Cached in memory and on disk as well. So we need
- An in-memory dictionary to store images
- Save image to disks after downloading, possible to specify where to save. e.g FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask) will make image saved in /Users/{user-name}/Library/Developer/CoreSimulator/Devices/{device-id}/data/Containers/Data/Application/{app-id}/Library/Caches/
- Try fetch from memory first, if not in memory then try fetch from sandbox and read into memory. Download only it is not in memory neither on disk. Check AlamofireImage to see how to find where the image is cached
Multi-threading
- Use OperationQueue to manage the parallel downloading tasks
- For each downloading task, we create an BlockOperation and add it to OperationQueue, so the downloading task will be executed on separate thread instead without blocking UI.
- Also need a dictionary to record for each image, whether we have already created an operation. Since the demo is based on tableView, when cell is scrolled into view(dequeued into memory) we don't want to duplicate the downloading task.
- Calling image updating completion on main thread DispatchQueue.main.async
Further improvement
- Suspend operation if the cell is not in the view, especially when you scrolling down/up very quick.
- Check cell is not in view: func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath)
No comments:
Post a Comment