简体   繁体   中英

How To Read Images From NSMainBundle in iOS

I have the structure like the following in my Xcode project.

在此处输入图片说明

I need to read all the images from project and need to store it in array.

I have used the following code from some other StackOverflow posts, but it's not working.

NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Images"ofType:@""];
NSDirectoryEnumerator *direnum;
direnum = [fileManager enumeratorAtPath: filePath];
imageFolder = [NSMutableArray new];
for(NSString *filename in direnum){
    if([[filename pathExtension] isEqualToString:@"png"]){
        [imageFolder addObject:filename];
    }
}
NSLog(@"Files in the folder %@",imageFolder);

I would appreciate, if any one help me to complete this.

it's simple to get all the images into a array

NSBundle *imageBundle=[NSBundle bundleWithPath: myBundlePath];
NSArray *allImageURLs=[imageBundle URLsForResourcesWithExtension:@"png" subdirectory:nil];

- (NSArray *)pathsForResourcesOfType:(NSString *)extension inDirectory:(NSString *)subpath将为您提供所需的数组。

NSArray *imagesArray = [[NSBundle mainBundle] pathsForResourcesOfType:@"png" inDirectory:@"Images"];

You can try below

NSArray *pathArray = [[NSBundle mainBundle] pathsForResourcesOfType:@"png" inDirectory:nil];

[pathArray enumerateObjectsUsingBlock:^(NSString *pathString, NSUInteger idx, BOOL *stop) {

    UIImage *yourImage = [[UIImage alloc] initWithContentsOfFile:pathString];
}];

Please use this code, hope it will work.

    NSString *dirPath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"images"];
    NSError * error;
    NSArray * images =  [[NSFileManager defaultManager]
                  contentsOfDirectoryAtPath:dirPath error:&error];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM