首页 > 解决方案 > Swift:如何提高从文档中加载图像的速度?

问题描述

我的应用程序将照片保存到本地文档文件夹,我使用 UICollectionView 显示该文件夹中的所有图像。但是每当我尝试打开 CollectionView 时,它通常需要几秒钟才能打开。我在想可能是图像文件太大,每张照片大约 10MB。我也尝试使用缩略图在 collectionview 中显示,但它仍然太慢。知道如何加快速度吗?

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! SPCell
    // Configure the cell
    cell.imageView.image = loadImage(fileName: self.fileURLs[indexPath.row])
    return cell
}
func loadImagesFromDocuments(){
    let fileManager = FileManager.default
    let documentsURL = NSHomeDirectory() + "/Documents/Secure/"
    do {
        fileURLs = try fileManager.contentsOfDirectory(at: URL(string: documentsURL)!, includingPropertiesForKeys: nil)
    } catch {
        print("Error while enumerating files : \(error.localizedDescription)")
    }

}

func loadImage(fileName: URL) -> UIImage? {
   do {
        let imageData = try Data(contentsOf: fileName)
        return UIImage(data: imageData)
    } catch {
        print("Error loading image : \(error)")
    }
    return nil
}

标签: iosswift

解决方案


当前的问题是每次出现单元格时都会加载图像,而不是

var fileURLs = [URL]()

做了

var fileImages = [UIImage]()

然后在里面viewDidLoad

fileImages = fileURLs.compactMap { self.loadImage(fileName: $0) }

推荐阅读