How can we get all file names starting with a prefix from resource folder..
Updated for Swift 4.0:
In my case, I was looking for files that began with fileName-1.png
where there might be other files with the fileName
prefix.
1) I thought about using regex, but splitting the string was faster and easier, so I went that route to get the prefix.
let myKnownFileNameString = "fileName-1.png"
let filePrefix = myKnownFileNameString.split(separator: "-").first
2) Create an empty array to store images you find:
var imageArray: [UIImage] = []
3) Then, get the URLs from the bundle, filter
them and map
the URLs to UIImage
instances:
if let filePrefix = filePrefix, let fileURLs = Bundle.main.urls(forResourcesWithExtension: "png", subdirectory: nil) {
imageArray = fileURLs.filter{ $0.lastPathComponent.range(of: "^\(filePrefix)", options: [.regularExpression, .caseInsensitive, .diacriticInsensitive]) != nil }
.map{ UIImage(contentsOfFile: $0.path)! }
}
From there, you've got an array of images that you can do stuff with (animate them in a UIImageView
, etc.)