【发布时间】:2019-10-11 13:30:17
【问题描述】:
我正在将图像从 RESTApi 加载到像 ScrollView 这样的 Netflix 中。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ccell", for: indexPath) as! CollectionCell
cell.imageView.image = nil
cell.labelText.text = self.data[indexPath.row].kategorie
cell.model = self.data[indexPath.row].model!
cell.progressHud.startAnimating()
let url = self.data[indexPath.row].thumbnail_image_name
if let imageFromCache = imageCache.object(forKey: url as AnyObject) as? UIImage{
cell.imageView.image = imageFromCache
}else{
Download.fetchPhoto(id: 1, url: self.data[indexPath.row].thumbnail_image_name) { (image) in
DispatchQueue.main.async {
cell.imageView.image = image
cell.progressHud.stopAnimating()
}
self.imageCache.setObject(image, forKey:url as AnyObject)
}
}
return cell
}
我将图像缓存在 ImageCache 中。到现在为止还挺好。问题是,每次我打开 TableviewController 时,下载任务都会重新开始。下载图像后保存图像的最佳做法是什么,即使在演示 vc 已关闭之后也是如此。
将它们保存到设备中? 在关闭时,将缓存发送回呈现的 vc 吗?
也许你有一些想法。
谢谢!
【问题讨论】:
-
这将是一个疯狂的猜测,但我认为
imageCache是你的TableViewController上的一个变量,所以每当你打开TableViewController它也会重置。您需要做的是将imageCache变量存储在单例共享实例中,然后使用它。