ios - swift 3 : Caching images in a collectionView

标签 ios swift xcode swift3

我目前正在研究我的应用程序,更新它以使用 Swift 3,但还有一个问题。以前,我的图像缓存工作得很好,但自从更新后,UIImageView 在获取图像时不会被填充。

这是代码(在 ...cellForItemAt... 函数中):

if let img = imageCache[imageUrl] {
    print("CACHE HIT: \(indexPath)")
    cell.image.image = img
} else {
    print("CACHE MISS: \(indexPath)")
    var imgUrl: = URL(string: imageUrl)
    let request: URLRequest = URLRequest(url: imgUrl!)
    let dataTask = session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in
        if(data != nil) {
            print("IMAGE DOWNLOADED: \(imgUrl?.query))")
            let image = UIImage(data: data!) // create the image from the data
            self.imageCache[imageUrl] = image // Store in the cache
            DispatchQueue.main.async(execute: {
                if let cell = collectionView.cellForItem(at: indexPath) as? MyCollectionViewCell {
                    print("APPLYING IMAGE TO CELL: \(indexPath)")
                    cell.image.image = image
                    self.collectionView.reloadData()
                } else {
                    print("CELL NOT FOUND: \(indexPath)")
                }
            })
        } 
    }) 
    dataTask.resume()
}

如您所见,我添加了一些 print 以了解发生了什么。当 View 加载时,我可以看到缓存未命中、图像加载和 UIImageView 正在为可见行填充,但是当我向下滚动时,UIImageView 是从未填充,日志显示每个 indexPath 的 CELL NOT FOUND: [0, x]

如果我在向下滚动后再次向上滚动,图像会按预期从缓存中填充。

自上一版本的 Swift/iOS/Xcode 以来,代码没有改变,并且曾经完美地工作。

我对任何第 3 方扩展等不感兴趣;我想了解上面的代码有什么问题。但是,欢迎对代码提出任何其他改进/建议。

任何想法将不胜感激!

最佳答案

与其通过 cellForItem(at: indexPath) 方法获取单元格,不如使用您用来在缓存命中中设置图像的 cell 变量。这将创建对单元格 ImageView 的强引用。

DispatchQueue.main.async(execute: { [weak collectionView] in
    cell.image.image = image
    collectionView?.reloadData()
})

考虑将 UIImageView 重命名为 imageView 而不是 image

关于ios - swift 3 : Caching images in a collectionView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39561572/

相关文章:

ios - Swift:从另一个类调用函数以出现在同一个 WebView 中

ios - 在 Swift 数组上使用过滤器会给出 "cannot invoke filter with an argument list of type (Object) throws -> Bool,"但参数不会抛出

ios - 如何在Xcode8中模拟应用程序终止?

ios - MacOS High Sierra 升级后 Xcode Server Gym 失败

ios - 如何在 iOS SDK 中获取 Spotify 刷新 token

swift - 如何在swift中按 bool 字段对数组进行排序?

c - 为什么设置断点会使我的代码工作?

ios - 安装企业 .ipa 时获取 "Unable to Download App"

ios - 在 View Controller 中隐藏/显示控件

ios - Xcode 5.1.1 未加载且无法连接 iPad