I'm using Firebase
to load my images into my cell's ImageView
but! there is a problem. I'm using caching mechanism for preventing images to redownload when reusable cells
loads but the images do not load until i've scroll my TableView
.
Here is the code;
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
cell.imgv.image = nil
if let urlString = self.filteredFlats[indexPath.row].flatThumbnailImage?.imageDownloadURL
{
imageURLString = urlString
let url = URL(string: urlString)
if let imagefromCache = imageCache.object(forKey: urlString as AnyObject) as? UIImage
{
DispatchQueue.main.async {
cell.imgv.image = imagefromCache
return
}
}
else
{
URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
DispatchQueue.main.async {
let imagetoCache = UIImage(data:data!)
if self.imageURLString == urlString
{
cell.imgv.image = imagetoCache
}
self.imageCache.setObject(imagetoCache!, forKey: urlString as AnyObject)
}
}).resume()
}
}
return cell
}
I think the problem is, when URLSession
downloaded the image and set it into ImageView
, but the loaded image is not showing up until the indexpath.row
called back when scrolling up and down.
I realized that the cause of it is this if statement;
if self.imageURLString == urlString
But if i remove it, the cells getting worse coz of reusable cell's behaviour. Some cells still showing the old cached images.
Really does not aware of what is going on. Was not expecting that TableViews
are kind of complex structure as it is.
Thanks.