How to get path of image form Resource of main bun

2019-04-26 15:41发布

i have an iPhone application in which i added images directory (Group) in to Resources (group). i want to access that images which is in images. I need a path to that images so i create a code like following.

NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"myImage1" ofType:@"png" inDirectory:@"images"];
NSLog(@"%@", imagePath);

Result :

(null)

i also tried this code

NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"myImage1" ofType:@"png"];

But this code gives me (null) result.

myImage1 's path is Resources/images/myImage1.png

I don't know what is the problem. Please suggest some fixes.

3条回答
唯我独甜
2楼-- · 2019-04-26 15:45

Adding image by following method solved my problem.

  • Right click on project in xcode and select Add Files to "project name".
  • Select your image file from computer local disk.
  • In the pop-up window make sure you select Copy items into destination group's folder and Create Folder References for any added folders and Add to targets.
  • click Add.

Then with bellow code i can retrieve my image.

For Objective-C version

[[NSBundle mainBundle] pathForResource:@"imageName" ofType:@"png"];

For Swift 4.0 version

Bundle.main.path(forResource: "imageName", ofType: "png")
查看更多
我命由我不由天
3楼-- · 2019-04-26 15:53

First of all Check if there is a file with name name in the main Bundle.

It gives null when there is no file with such a name.

查看更多
啃猪蹄的小仙女
4楼-- · 2019-04-26 16:11

for soultion....

Go to : Target -> "Build Phases" -> "copy bundle Resources" Then add that particular file here.

clean the project and RUN. It works.

and also see...

NSBundle pathForResource inDirectory gives nil

and also check...

NSString *path = [[NSBundle mainBundle] resourcePath];
NSFileManager *fm = [NSFileManager defaultManager];
NSError *error = [[NSError alloc] init];
NSArray *directoryAndFileNames = [fm contentsOfDirectoryAtPath:path error:&error];

print all value of this directoryAndFileNames and check your filename is exist in that or not....

查看更多
登录 后发表回答