I hope you're all doing great!
I'm working on an iOS app where I need to load a set of images that I've added manually to the app's resource bundle. The images are stored inside a known top-level folder, and within that, there are subfolders, each containing a set of image files.
My goal is to dynamically load all the image files without hardcoding their names, so I can display them to the user in a list or grid.
Here's the folder structure in my Xcode project:
Resources/
└── Stickers/
├── Animals/
│ ├── cat.png
│ └── dog.png
└── Emojis/
├── smile.png
└── wink.png
I'm looking for a way to:
Access the Stickers/ directory from the bundle Loop through all subdirectories Collect the full paths of image files to display Any help or recommended approach would be appreciated!
Thanks in advance 🙏
create a model class in which you need to define which values you want to add
struct StickerCategory {
let name: String
let imagePaths: [String]
}
func loadStickers() -> [StickerCategory] {
guard let stickersURL = Bundle.main.url(forResource: "yourStickerName", withExtension: nil) else {
print("Stickers directory not found")
return []
}
var categories = [StickerCategory]()
do {
let categoryURLs = try FileManager.default.contentsOfDirectory(
at: stickersURL,
includingPropertiesForKeys: [.isDirectoryKey],
options: [.skipsHiddenFiles]
)
for categoryURL in categoryURLs {
let isDirectory = try categoryURL.resourceValues(forKeys: [.isDirectoryKey]).isDirectory ?? false
if isDirectory {
let categoryName = categoryURL.lastPathComponent // you can extract categoryName as name of the sticker
let imageURLs = try FileManager.default.contentsOfDirectory(
at: categoryURL,
includingPropertiesForKeys: nil,
options: [.skipsHiddenFiles]
).filter { url in
let pathExtension = url.pathExtension.lowercased()
return ["png", "jpg", "jpeg"].contains(pathExtension)
}
let imagePaths = imageURLs.map { $0.lastPathComponent } // here you can get the imagePath
categories.append(StickerCategory(name: categoryName, imagePaths: imagePaths))
}
}
} catch {
print("Error loading stickers: \(error)")
}
return categories
}
// how to use example:
let loadAllStickers = loadStickers()
it will give an array of all objects, you just need to load in your cell and using name of that sticker, and load iamge from imagePath using following code
for category in stickerCategories {
// if you want to print categoryaname
for imagePath in category.imagePaths {
// let image = UIImage(contentsOfFile: imagePath) // load image from this path
}
}