0

I'm trying to save images in cache so that when I scroll up and down it doesn't have to download these images again. Unfortunately this doesn't seem to work because after all the images are downloaded when I scroll network activity goes up. Any ideas?

 let cache = NSCache<NSString, UIImage>()

 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: idForCell, for: indexPath)

        let usr = userList[indexPath.row]
        cell.textLabel?.text = usr.name
        cell.detailTextLabel?.text = usr.email

        if cell.imageView?.image != nil{
            return cell
        }

        let key = NSString(string: usr.imgUrl!)

        if cache.object(forKey: key) != nil{
            cell.imageView?.image = cache.object(forKey: key)! as UIImage
            return cell
        }

        if let imgUrl = usr.imgUrl{
            let url = NSURL(string: imgUrl)
                URLSession.shared.dataTask(with: url as! URL, completionHandler: { (data, resp, err) in
                    if err != nil{
                        print(err!)
                        return
                    }

                    DispatchQueue.main.async {
                        cell.imageView?.image = UIImage(data: data!)
                        self.cache.setObject((cell.imageView?.image)!, forKey: NSString(string: imgUrl))
                        cell.setNeedsLayout()
                    }

                }).resume()
        }
        return cell
   }
Himanshu Moradiya
  • 4,769
  • 4
  • 25
  • 49
  • Your use of NSCache looks reasonable. You're going to need to provide more info than "network activivity goes up" in order to figure out what's going on. – Duncan C Dec 24 '16 at 12:47
  • 1
    Note that your code that checks to see if the dequeued cell already has an image is wrong. The existing image in a recycled cell is almost certain to be the wrong image. – Duncan C Dec 24 '16 at 12:48
  • Also note that you are abusing the `!` force-unwrap operator. If any of the optionals you're force-unwrapping are nil, your code is going to crash. You should use `guard`, `if let`, or `??` instead. – Duncan C Dec 24 '16 at 12:48
  • As far as the caching process goes everything looks good to me. I would look at: is the image being saved to the cache? If so what is the key? Does it match up? – Garret Kaye Dec 24 '16 at 16:12
  • cache gets some elements but keys never match :/ – Michael Metreveli Dec 25 '16 at 15:06

0 Answers0