Question

I have done a lot of research to find the difference between the working of the codes below . As im trying to fetch the image from the Document Directory that can be specified by PATH using NSBundle and show it in ImageView.

TYPE 1: This code is working fine and able to retrieve the image and display :

NSString *inputPath= @"/Users/abc/Library/Application Support/iPhone Simulator/6.0/Applications/ADD46F96-333A-46BF-8291-FABD1BD7C389/Documents/colour.png";
NSString *jjj=[inputPath pathExtension];
NSString *hhhhh=[[inputPath lastPathComponent]stringByDeletingPathExtension];
NSString *bivivik=[inputPath stringByDeletingLastPathComponent];
NSString *imagePATH=[NSBundle pathForResource:hhhhh ofType:jjj inDirectory:bivivik];
theImage=[UIImage imageWithContentsOfFile:imagePATH];
mImageDisplayView.image=theImage;

TYPE 2: But if i try as below code .Not fetching the image and showing null value

NSString* imagepath = [[NSBundle bundleWithPath:@"/Users/abc/Library/Application Support/iPhone Simulator/6.0/Applications/ADD46F96-333A-46BF-8291-FABD1BD7C389/Documents/colour.png"]bundlePath];
theImage=[UIImage imageWithContentsOfFile:imagepath];
mImageDisplayView.image=theImage;

What is the wrong with my TYPE 2 code .Is there any other way which i can fetch the image as im trying in TYPE 2 method .please help me

Was it helpful?

Solution

Even though the code above works in one instance, both the code snippets are wrong because they will fail to read the file on device. Reason is, you are using the absolute path from your MAC which simulator is able to find, however will not exist on device.

Use [NSBundle mainBundle] to read file from application bundle,

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

For reading file from documents directory of your application use this code snippet,

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Myfile.png"];
UIImage *image = [[UIImage alloc] initWithContentsOfFile:filePath];

EDIT

If you have a separate bundle which contains image files then to read from that bundle use this snippet. Assuming that this bundle is in documents directory,

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *bundlePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"MyBundle.bundle"];
NSBundle *myBundle = [NSBundle bundleWithPath:bundlePath];
NSString* imagePath = [myBundle pathForResource:@"MyImage" ofType:@"png"];
UIImage *image = [[UIImage alloc] initWithContentsOfFile:imagePath];

Hope that helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top