【问题标题】:Loading Images in to TableViewController将图像加载到 TableViewController
【发布时间】: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 变量存储在单例共享实例中,然后使用它。

标签: swift xcode uikit


【解决方案1】:

因为您的下载方法是在cellForRow 中调用的,所以每次新单元格出列时都会获取该方法。

我建议在viewDidLoad() 中进行下载,并将下载的图像保存到您的单元格可以引用的数组中。下载完成后,您可以告诉您的集合视图重新加载其数据。

如果您不想每次看到屏幕时都下载图像,则需要保留下载的图像数据,然后您可以访问该数据,而不是在viewDidLoad() 中调用下载。

【讨论】:

  • 我有一个 LaunchViewController 正在处理一些下载任务。实际上,让用户在启动期间等待可能比每次显示滚动视图时让他们等待更好。我会将图像下载任务添加到该控制器...谢谢
  • @Aknitt 这不是一个非常人性化的体验,每次应用启动时都要等待应用下载图像。为什么不使用 Kingfisher 下载图像,它在后台线程上执行此操作,您可以在下载图像时显示加载指示器或占位符图像。 Kingfisher 自己处理它的 imageCache,因此下次您不必再次下载相同的图像。此外,翠鸟是高度可修改的。看看吧here
猜你喜欢
  • 2015-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多