tags:

views:

1887

answers:

3

Question about bundles and file access.

I've adding a series of folders to my project (using the Add existing file option). This results in the folder contents being shown in Xcode as a blue folder.

The following works:

NSString *imageName = [NSString stringWithFormat:@"/File-03/images/image-%02d.jpg", imageIndex];

return [UIImage imageNamed:imageName];

However, I want to switch to using imageWithContentsOfFile so the images are not cached.

The code below returns nil for the image:

return [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"/File-03/images/image-%02d.jpg", imageIndex]];

I also tried accessing the imageWithContentsOfFile using a bundle, no go.

What am I missing here?

Thanks!

+2  A: 

To access and store files on the iPhone I recommend reading this.

Erica Sadun has also written a nice shorty about accessing file within a app bundle.

Note that how files are organized in Xcode does not show how they will end up in the app bundle. The best way is to select the app bundle in the Finder and CTRL-click and select Show Package Content.

epatel
What happens if I add my content to the bundle via Show Package Content?
Johan Carlsson
Think that will break the codesign and it will not run on a device
epatel
A: 

Okay, I figured out one way in code to get what I needed:

  NSString *dir = [NSString stringWithFormat:@"File-03/images", imageIndex];
  NSString *file = [NSString stringWithFormat:@"image-%02d", imageIndex]; 
  NSString *path = [[NSBundle mainBundle] pathForResource:file ofType:@"jpg" inDirectory:dir];

  return = [UIImage imageWithContentsOfFile:path];

The trick was to inDirectory in the bundle call.

John
NSString *dir = @"File-03/images";Should be sufficent, no?
Andrew Pouliot
+1  A: 

The problem with your imageWithContentsOfFile code is that you're assuming that / is the root of the bundle, when it's the root of the FS!

So, pathForResource:ofType:inDirectory: is probably the easiest way to get the path you need.

Otherwise, you can get the root of the bundle and prefix that to your paths.

Andrew Pouliot