A lightweight iOS image cache with built in queue management.
pod 'SGImageCache'
// Objective-C
[SGImageCache getImageForURL:url thenDo:^(UIImage *image) {
if (image) {
self.imageView.image = image;
}
}];// Swift
SGImageCache.getImageForURL(url) { image in
if image {
self.imageView.image = image
}
}This will add the fetch request to fastQueue (a parellel queue). All image fetching (either
from memory, disk, or remote) is performed off the main thread.
// Objective-C
[SGImageCache slowGetImageForURL:url thenDo:nil];// Swift
SGImageCache.slowGetImageForURL(url, thenDo: nil)This will add the fetch request to slowQueue (a serial queue). All image fetching (either
from memory, disk, or remote) is performed off the main thread.
Adding image fetch tasks to slowQueue is useful for prefetching images for off screen
content. For example if you have data for 100 table rows, but only 3 are on screen at a time,
you would request the images for on screen rows from fastQueue with getImageForURL: and
add the rest to slowQueue with slowGetImageForURL:.
// Objective-C
[SGImageCache moveTaskToSlowQueueForURL:url];// Swift
SGImageCache.moveTaskToSlowQueueForURL(url)This is useful for deprioritising image fetches for content that has scrolled off screen. The content may scroll back on screen later, so you still want the fetch to happen, but it is no longer urgently required.
fastQueue is a parallel queue, used for urgently required images. The getImageForURL:
method adds tasks to this queue. The maximum number of parallel tasks is managed by iOS, based on the device's number of processors, and other factors.
slowQueue is a serial queue, used for prefetching images that might be required later (eg
for currently off screen content). The slowGetImageForURL: method adds tasks to this queue.
slowQueue is automatically suspended while fastQueue is active, to avoid consuming network bandwidth while urgent image fetches are in progress. Once all fastQueue tasks are completed
slowQueue will be resumed.
If an image is requested for a URL that is already queued or in progress, SGImageCache
reuses the existing task, and if necessary will move it from slowQueue to fastQueue,
depending on which image fetch method was used. This ensures that there will be only one
network request per URL, regardless of how many times it's been asked for.