目标是从目录中获取图像名称,并将它们添加到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 {这就是我遇到的问题:错误:找到零(让图像)
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]
}发布于 2020-08-04 18:09:45
问题是--正如您正确地提到的-- 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
}https://stackoverflow.com/questions/63252574
复制相似问题