My image assets catalog has a folder named \"Nature\" with hundreds of image files inside.
I would like to get an array of image file names under the \"Nature\" dire
I know there are 2 ways to get an array of image files.
In assets use the same prefix for all your images and append an incrementing number:
then you can:
for (int i = 1; i <= 6; i++) {
UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"bg_button%d", i]];
NSLog(@"%@", image);
}
Create folder references rather than image assets
So we can get an array of image files using this snippet:
NSString *directory = [NSString stringWithFormat:@"Intro"];
NSArray *intros = [[NSBundle mainBundle] pathsForResourcesOfType:@"png" inDirectory:directory];
NSLog(@"%@", intros);
Hope this did help you!
this may be late but this might helps others
you can not directly access all the file from assets as its compiled to .car
alternative to access the all files from the assets is to create the .plist file with the all images that assets contains and plist file can be easily accessible. following are the steps to achieve this
Step 1: add script in Build Phases -> Run Script
echo "<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>" > ${SRCROOT}/${PROJECT_NAME}/files.plist;
## Chnage Assets.xcassets if not using default one
find ${SRCROOT}/${PROJECT_NAME}/Assets.xcassets -type f -not -iname "*@*" -name "*.png" -exec basename {} \; | while read line; do echo \<key\>$line\</key\>\<string\>$line\</string\>; done >> ${SRCROOT}/${PROJECT_NAME}/files.plist;
echo "</dict></plist>" >> ${SRCROOT}/${PROJECT_NAME}/files.plist;
this script generate files.plist in project directory with all images in assets file add this file to project
Step2: Accessing plist file
NSURL *filepath = [[NSBundle mainBundle] URLForResource:@"files" withExtension:@"plist"];
NSMutableDictionary *allXCAssetsImages = [NSMutableDictionary dictionaryWithContentsOfFile:filepath.path];
I've searched this problem and get the conclusion that you could not access the IncludedStudyImages
directory directly. Check these:
Access Asset Catalog pathForResource
Can I get a NSURL from an XCAssets bundle?
Another way work around is that you could predefine the file name according to some order. For example names like "image1.png", "image2.png", "image3.png". And using this way you could do the selecting a random image feature.