Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically access image assets

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" directory in my image assets. I will then choose a random image name from this array and display it with [UIImage imageNamed:@"..."]. I am stuck on how to get an array of image names under the 'IncludedStudyImages' directory. I cannot even find anything in the documentation on how to interact with my image assets programmatically (other than displaying them).

Thanks for your help.

like image 405
Dan Avatar asked Apr 26 '26 07:04

Dan


2 Answers

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 enter image description here

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];
like image 174
Meghs Dhameliya Avatar answered Apr 28 '26 20:04

Meghs Dhameliya


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:
Image names with 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

When importing images choose create folder references
Images in folder

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!

like image 40
Bannings Avatar answered Apr 28 '26 22:04

Bannings