1

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()
}
}
Swift
  • 1,074
  • 12
  • 46
Visal Sambo
  • 1,270
  • 1
  • 19
  • 33
  • Take the benefit of some third party libraries (SDWebImages or KingFisher).They do image caching in better way and handle some more scenarios. – Vikky Aug 02 '18 at 05:34

2 Answers2

2
 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()
    }
}

}

1

You can instead use the Kingfisher library , handles the image caching itself you don't need to worry about it. For implementing see : https://github.com/onevcat/Kingfisher

with just one line of code you can set the image

imgView.kf.setImage(with: ImageResource(downloadURL: URL(string: imgUrl)!))
Shahzaib Qureshi
  • 989
  • 8
  • 13