Reputation: 823
So I had this argument at work about what's better for downloading images in a UITableView's cells.
The two options are: In the cellForRowAtIndex, I download the image asynchronously which leads to using multiple threads and multiple network requests which we suspect may be the issue for battery drain.
The other option is to download all the images at once using one thread and one network request, by looping through an array with all the images' URLs outside the cellForRowAtIndex of coarse, and then calling the the table view reload function.
There is also a slight modification for latter approach where we can set each image (perhaps by calling the reload function) as soon as each image is downloaded.
So I would love to know, what's the industry standard way of handling this? What are the pros and cons especially when it comes to performance? Are there any better ways?
Upvotes: 1
Views: 3539
Reputation: 41
Best practices are below for me;
For battery consumption;
Based on Apple's energy efficiency guide, it is better to download items in bulk compared to download one by one. But, there is a tread-off here. In my opinion, performance has the highest priority here compared to battery consumption.
Upvotes: 1
Reputation: 775
I generally use SDWebImage, it caches the images and can be reused later. It provides flexibility with its extensions and various methods.
Check my implemented code:
import UIKit
import SDWebImage
extension AcceptedWinksViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Constants.CellIdentifier.WinkListTableViewCell) as! WinkListTableViewCell
let profile = self.winkList[indexPath.row] //Model
let placeHolderImage = UIImage(named:"placeHolder") //your placeholder image, can be class or global variable
if let url = profile.imageURL {
cell.userImageView.sd_setImage(with: url, placeholderImage: placeHolderImage, options: .refreshCached, completed: nil) //check its various options
}
else {
cell.userImageView.image = placeHolderImage
}
return cell
}
}
Upvotes: 4