I am facing a very strange problem. My UICollectionView is rendering the same image for multiple cells. I am loading images from external sources. Here is my code.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: TTElementViewCell? = collectionView.dequeueReusableCell(withReuseIdentifier:reuseIdentifier, for: indexPath) as? TTElementViewCell
cell?.imageView.image = UIImage(named:"dummyImage.png")
let uniqueImageName = TTApplicationModel.sharedModel.cacheKey(fbUrl: crItem.profileImageUrl)
DispatchQueue.main.async {
cell?.load(cacheKey: uniqueImageName, url: crItem.profileImageUrl)
}
return cell!
}
Here is my load function inside a custom cell class named TTElementViewcell
which extends UICollectionViewCell
.
func load(cacheKey:String,url:String){
let loader = TTAsyncImageLoader()
let uniqueImageName = TTApplicationModel.sharedModel.cacheKey(fbUrl: url)
if uniqueImageName != ""{
loader.load(cacheKey: uniqueImageName, url: URL(string:url)!, completion: { (image:UIImage?) in
DispatchQueue.main.async {
self.imageView.image = image!
}
})
}
}
Here is the details of TTAsyncImageLoader
class.
import UIKit
class TTAsyncImageLoader {
fileprivate let model = TTApplicationModel.sharedModel.imageCache
private func getDataFromUrl(url: URL, completion: @escaping (_ data: Data?, _ response: URLResponse?, _ error: Error?) -> Void) {
URLSession.shared.dataTask(with: url) {
(data, response, error) in
completion(data, response, error)
}.resume()
}
func load(cacheKey:String, url:URL,completion:@escaping (_ success:UIImage?)->Void) {
if let image = self.model.object(forKey: cacheKey as AnyObject) as? UIImage{
completion(image)
return
}
self.getDataFromUrl(url: url) { (imgData:Data?, response:URLResponse?, error:Error?) in
if error == nil{
self.model.setObject(UIImage(data: imgData!)!, forKey: cacheKey as AnyObject)
completion(UIImage(data: imgData!)!)
}else{
print("TTAsyncImageLoader::load \(error!.localizedDescription) ")
}
}
}
}
The output is shown in the image: