【问题标题】:SWIFT 5.1 Get array of strings ( image names ) from directory and append to an array of UIImagesSWIFT 5.1 从目录中获取字符串数组(图像名称)并附加到 UIImages 数组
【发布时间】:2020-11-24 21:15:35
【问题描述】:

目标是从目录中获取图像名称并将它们添加到 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 添加到集合视图以提取图像。

 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]
 }

【问题讨论】:

    标签: arrays swift null uicollectionview


    【解决方案1】:

    问题在于——正如你正确提到的——contentsOfDirectory(atPath 返回一个 图像名称 数组。要从磁盘读取图像,您需要完整路径。

    我推荐使用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
    }
    

    【讨论】:

    • 这将不必要地将位于 Documents 目录中的所有文件加载到内存中,即使它们不是图像。我至少会检查 URL 类型标识符以过滤所需的类型。大于可用内存的文件可能会冻结/崩溃应用程序。
    • 可能类似于 if let typeIdentifier = (try? url.resourceValues(forKeys: [.typeIdentifierKey]))?.typeIdentifier, ["public.image","public.png","public.jpeg"].contains(typeIdentifier), 或至少检查 URL pathExtension
    • 这在“文档”的子目录中,其中只有图像。我发现为特定文件类型创建单独的文件夹会更好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多