swift 4、如何在collectionView中加载超过3000~张图片?

swift 4, how do I load over 3000~ pictures in collectionView?

我正在使用 UICollectionView 制作相册。 我在 iPhone 7 上加载了图片。我让它加载了大约 2000 张图片,但是如果我向下滚动 UICollectionView 时有超过 3000 张图片,它会非常慢,有时应用程序会停止。

我正在使用此代码获取图片。

extension UIImageView {
    func fetchImage(asset: PHAsset, contentMode: PHImageContentMode, targetSize: CGSize) {
        let options = PHImageRequestOptions()
        options.version = .original
        options.isSynchronous = true
        PHImageManager.default().requestImage(for: asset, targetSize: targetSize, contentMode: contentMode, options: options) { image, _ in
            guard let image = image else { return }
            switch contentMode {
            case .aspectFill:
                self.contentMode = .scaleAspectFill
            case .aspectFit:
                self.contentMode = .scaleAspectFit
            }
            self.image = image
        }
    }
}

我做了一个let imageCache = NSCache<NSIndexPath, UIImage>() 并在 cellForItem 中使用了它。但这对解决这个问题没有帮助。 还有其他方法吗?

而且我连续得到 3 张图片,大小为 self.view.frame.width / 2

如果没有办法。我必须获得较小尺寸的图像吗?

cellForItem代码:

let imageCache = NSCache<NSIndexPath, UIImage>()

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "albumCell", for: indexPath) as? AlbumCollectionViewCell

    let asset: PHAsset? = AlbumModel.allPhotos?.object(at: indexPath.row)

    cell!.albumImageView.contentMode = .scaleAspectFill
    if let fromImageCache = imageCache.object(forKey: indexPath as NSIndexPath) {
        cell!.albumImageView.image = fromImageCache
        return cell!
    }

    let setSize = CGSize(width: view.frame.width / 2, height: view.frame.width / 2)
    cell!.albumImageView.fetchImage(asset: asset!, contentMode: .aspectFill, targetSize: setSize)

    imageCache.setObject(cell!.albumImageView.image!, forKey: indexPath as NSIndexPath)
    return cell!
}

如果你一次加载 3000 张图片会导致内存问题应用程序将被终止为什么应用程序停止更好你可以使用CollectionView分页加载3000张图片

以下是滚动浏览照片库时提高性能的一些提示:

不要实现您自己的图像缓存或使用默认图像管理器,使用您自己的 PHCachingImageManager 实例。您可以告诉它开始缓存滚动位置周围的图像以提高性能。

不要使用同步获取图像。使用异步方法并在完成块中更新图像视图,但请注意,完成块甚至可以在 fetch 方法返回之前触发,并且当您从库中获得质量更好的图像时触发多次。

当您的单元格离开屏幕时取消提取。

我有一段时间没有使用该框架了,但我写了一些关于它的笔记 here 希望它们仍然有用。