SWIFT 5.1 从目录中获取字符串数组(图像名称)并附加到 UIImages 数组

SWIFT 5.1 Get array of strings ( image names ) from directory and append to an array of UIImages

目标是从目录中获取图像名称并将它们添加到 UIImages 数组中。

 var photoArray = [UIImage]()
 

 func getImageFromDocumentDirectory() -> [UIImage] {
    let fileManager = FileManager.default
    var imageNames = [String]()
    let imagePath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, 
 .userDomainMask, true)[0] as NSString).appendingPathComponent("DIRECTORYNAME")
    do {
        let items = try fileManager.contentsOfDirectory(atPath: imagePath)
        for item in items {

这就是我遇到问题的地方:错误:发现 nil (let images)

 let images = UIImage(contentsOfFile: item)
 photoArray.append(images!)
        }
    } catch {
        print(error.localizedDescription)
    }
    return photoArray
}

将函数添加到集合视图以拉取图像。

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) 
 -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CELL", 
 for: indexPath) as! CELL

 let images = getImageFromDocumentDirectory()
 // photoImageView is a UIImageView in the cell.
 cell.photoImageView.image = images[indexPath.row]
 }

问题是 – 正如您正确提到的 – contentsOfDirectory(atPath returns 图像名称 的数组。要从磁盘读取图像,您需要完整路径。

我推荐使用URL相关的API

func getImageFromDocumentDirectory() -> [UIImage] {
    var images = [UIImage]()
    let fileManager = FileManager.default
    do {
        let documentsDirectoryURL = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
        let folderURL = documentsDirectoryURL.appendingPathComponent("DIRECTORYNAME")
        let urls = try fileManager.contentsOfDirectory(at: folderURL, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
        for url in urls {
            if let data = try? Data(contentsOf: url),
               let image = UIImage(data: data) {
                 images.append(image)
            }
        }
    } catch {
        print(error.localizedDescription)
    }
    return images
}