缓存无法保存tableView单元格图像

时间:2016-12-24 12:13:24

标签: ios swift uitableview cell nscache

我试图将图像保存在缓存中,这样当我向上和向下滚动时,它不必再次下载这些图像。不幸的是,这似乎不起作用,因为在我滚动网络活动后,所有图像都被下载了。有任何想法吗?

 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
   }

0 个答案:

没有答案
相关问题