swiftuicollectionviewnsurlsessionnscache

UIImage keeps loading all time when scroll even store in NSCache - swift


I am new in iOS programming. I am creating a simple app which loads image from a particular link ( firestore ). The images are completely downloaded from the server and visible on each cell of collectionview as usual. But the problem is that when when I scroll up or down then those images keeps loading again. I think it starts downloading again because when I turn off internet connection, those images are not being loaded anymore.

Here is how i set images in each cell

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! CollectionCell

    let explore = dataAppend[indexPath.item]
    //cell.imageDisplay.text = explore.title
    if let imageUrl = explore.image {
        cell.imageDisplay.loadImageWithData(urlString: imageUrl)
    }
    //print(explore.image)
    return cell
}

Here is how loading images look like loadImageWithData(urlString: imageUrl)

let imageCache = NSCache<NSString, UIImage>()

class CustomImageView : UIImageView {

var imageUrlString: String?

func loadImageWithData (urlString: String) {

    imageUrlString = urlString
    if let imageFromCache = imageCache.object(forKey: urlString as NSString){
        self.image = imageFromCache
    }
    image = nil
    let url = URL(string: urlString)
    URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in

        if let err = error {
            print(err.localizedDescription)
        }
        if let data = data {

            DispatchQueue.main.async {
                let imageToCache = UIImage(data: data)
                if self.imageUrlString == urlString {
                    self.image = imageToCache
                }
                imageCache.setObject(imageToCache!, forKey: urlString as NSString)
            }
        }
    }).resume()
}
}

Solution

  •  var imageCache = NSMutableDictionary()
    
    class CustomImageView: UIImageView {
    
    func loadImageUsingCacheWithUrlString(urlString: String) {
    
        self.image = nil
    
        if let img = imageCache.valueForKey(urlString) as? UIImage{
            self.image = img
             return 
        }
            let session = NSURLSession.sharedSession()
            let task = session.dataTaskWithURL(NSURL(string: urlString)!, completionHandler: { (data, response, error) -> Void in
    
                if(error == nil){
    
                    if let img = UIImage(data: data!) {
                        imageCache.setValue(img, forKey: urlString)    // Image saved for cache
                        DispatchQuee.main.asyn{
                           self.image = img
    
                    }
    
    
                }
            })
            task.resume()
        }
    }
    

    }