How to get path of image form Resource of main bundle
Solution 1
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
andCreate Folder References for any added folders
andAdd 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")
Solution 2
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....
Bhavin_m
iOS Developer with more than 9 years of experience in iPhone/iPad application development.
Updated on July 09, 2022Comments
-
Bhavin_m almost 2 years
i have an iPhone application in which i added
images
directory (Group) in toResources
(group). i want to access that images which is inimages
. 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 isResources/images/myImage1.png
I don't know what is the problem. Please suggest some fixes.
-
Bhavin_m about 11 yearsi get the file list and my
myImage1.png
is there in list. What next ?? -
Blacky over 8 yearsOne mistake, don't allocate the error, you should put "error = nil" and pass the address.
-
Blacky over 8 years"-[NSError init] called; this results in an invalid NSError instance. It will raise an exception in a future release." I tried to edit for you, but for some reason exception is not a good enough reason to edit on this site. I would never understand the logic of the admins here.