Swift:如何从资产中获取图像名称

时间:2016-10-31 14:21:20

标签: swift xcode image

我在资产中的文件夹中有500mb的图像。我不知道他们的名字。有没有办法访问它们...将它们存储到Array然后显示?

示例:我在Assets/folder1/folder2中存储了3张图片 文件夹2包含3张图片.....我需要获取这些名字。

enter image description here

这就是我需要这个的原因....我已经提供了汽车图像库,而且这些图像的名称不合逻辑。

enter image description here

2 个答案:

答案 0 :(得分:1)

在资产目录中存储图像时,您无法执行所描述的操作。从资产目录中获取资源取决于您知道其实际名称。

相反,请将这些文件夹直接存储在应用包的顶层。现在您有一个可以获得引用的实际文件夹,并可以向FileManager询问文件夹中图像的名称。

enter image description here

示例(Swift 2.2,抱歉):

let f = NSBundle.mainBundle().URLForResource("carPix", withExtension: nil)!
let fm = NSFileManager()
let arr = try! fm.contentsOfDirectoryAtURL(f, includingPropertiesForKeys: nil, options: [])
print(arr) // the URLs of the two jpg files

答案 1 :(得分:0)

上面的示例使用Swift 3

if let f = Bundle.main.url(forResource: "carPix", withExtension: nil) {
    let fm = FileManager()
    return try? fm.contentsOfDirectory(at: f, includingPropertiesForKeys: nil, options: [])
}
return nil