I am new to swiftUI and try to build an app that shows all images stored in a folder in assets. I have a piece of code that should look for jpg´s in assets and give back a string with the names of the images.
I tried printing out the "assetNames" but all I get is "[]"
this is my code:
func getPhotoNames() -> [String] {
let assetNames = Bundle.main.paths(forResourcesOfType: "jpg", inDirectory: "folder")
//let assetNames = ["5" , "6"]
print(assetNames)
return assetNames.map { URL(fileURLWithPath: $0).deletingPathExtension().lastPathComponent }
}
Assets.xcassets is not a folder but an archive containing all the images using Assets.car as its filename.
If you really want to read the assets file then you need to use some third party library that can extract it's contents like this one - Extractor.
If not you get use FileManager to get all images inside your bundle provided they're not inside your xcassets.
func getAllImageFiles() -> [String] {
var imageFiles: [String] = []
let fileManager = FileManager.default
if let enumerator = fileManager.enumerator(atPath: Bundle.main.bundlePath) {
for case let filePath as String in enumerator {
if filePath.lowercased().hasSuffix(".png") ||
filePath.lowercased().hasSuffix(".jpg") ||
filePath.lowercased().hasSuffix(".jpeg") {
imageFiles.append(filePath)
}
}
}
return imageFiles
}
and then use it like this -
let imageFiles = getAllImageFiles()
print(imageFiles)