首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SWIFT5.1从目录获取字符串数组(图像名称),并附加到UIImages数组中

SWIFT5.1从目录获取字符串数组(图像名称),并附加到UIImages数组中
EN

Stack Overflow用户
提问于 2020-08-04 17:56:10
回答 1查看 592关注 0票数 0

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

代码语言:javascript
复制
 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 {

这就是我遇到的问题:错误:找到零(让图像)

代码语言:javascript
复制
 let images = UIImage(contentsOfFile: item)
 photoArray.append(images!)
        }
    } catch {
        print(error.localizedDescription)
    }
    return photoArray
}

将功能添加到集合视图以提取图像。

代码语言:javascript
复制
 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]
 }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-08-04 18:09:45

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

我建议使用与URL相关的API

代码语言:javascript
复制
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
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63252574

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档