I want to build an image downloader for my UITableView
so images can be loaded asynchronously into the table view.
With NSURLSession
automatically using NSURLCache
to cache HTTP requests, will I be able to depend on that solely as my caching mechanism? I notice many use NSCache
to save the downloaded image, but if NSURLSession
already implements a cache, is that necessary? If anything, isn't it bad, as I'm duplicating a copy of the image in memory?
Furthermore, if it's possible, how do I use this in conjunction with UITableView
? Cell reuse presents an interesting issue with assigning the result of a background transfer.
I can't simply download the image using NSURLSessionDownloadTask
and in the completion block set the cell's image, as by the time it downloads the cell may have been reused and thus causing it to set it to the wrong cell.
let downloadTask = session.downloadTaskWithURL(URL, completionHandler: { location, response, error in
var dataFetchingError: NSError? = nil
let downloadedImage = UIImage(data: NSData.dataWithContentsOfURL(location, options: nil, error: &dataFetchingError))
dispatch_async(dispatch_get_main_queue()) {
// Might end up on the wrong cell
cell.thumbnail.image = downloadedImage
}
})
So how do I make sure that the assigned image makes its way to the correct cell, and that I'm caching these downloads properly?
I'm aware of SDWebImage and the like, but I'd like to try to solve this problem without the use of a library.