jpm jpm - 6 months ago 216
Objective-C Question

NSBundle path for resource return nil in iOS

I've a

bgs.bundle
which contains 20 images, I'm trying to load image_file.

NSString *bpath = [[NSBundle mainBundle] pathForResource:@"bgs" ofType:@"bundle"];
NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:bpath error:NULL];
for (NSString *fileName in files) {
NSString *filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"nil"];
if (filePath){
NSLog(filePath);
}else{
NSLog(@"file path is null");
}


filePath
is always null, I've also printed
fileName
which is working fine.
What can be the problem with my code or there is some other way to load files from bundle?

Answer

You main issue is that you attempt to load fileName from the main bundle instead of the bgs.bundle.

Change your code like this:

NSString *bpath = [[NSBundle mainBundle] pathForResource:@"bgs" ofType:@"bundle"];
NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:bpath error:NULL];
for (NSString *fileName in files) {
     NSString *filePath = [bpath stringByAppendingPathComponent:fileName];
     NSLog(@"filePath = %@", filePath);
}

Another option would be to get an NSBundle for bgs.bundle.

NSString *bpath = [[NSBundle mainBundle] pathForResource:@"bgs" ofType:@"bundle"];
NSBundle bgsBundle = [NSBundle bundleWithPath:bpath];

Now you can use bgsBundle as needed. Example:

NSString *filePath = [bgsBundle pathForResource:@"someImage" ofType:@"png"];
Comments