UIImage from file problem
I am trying to load an saved image but when I check the UIImage it co开发者_运维技巧mes back as nil. Here is the code:
UIImage *img = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"/var/mobile/Applications/B74FDA2B-5B8C-40AC-863C-4030AA85534B/Documents/70.jpg" ofType:nil]];
I then check img to see if it is nil and it is. Listing the directory shows the file, what am I doing wrong?
You need to point to the Documents directory within your app then like this:
- (NSString *)applicationDocumentsDirectory
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}
Usage:
UIImage *img = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/70.jpg",[self applicationDocumentsDirectory]]];
First, you are using pathForResource wrong, the correct way would be:
[[NSBundle mainBundle] pathForResource:@"70" ofType:@"jpg"]
The whole idea of bundling is to abstract the resource path such as that it will always be valid, no matter where in the system your app resides. But if all you want to do is load that image I would recommend you use imageNamed: since it automatically handles retina resolution (high resolution) display detection on the iPhone for you and loads the appropriate resource "automagically":
UIImage *img = [UIImage imageNamed:@"70.jpg"];
To easily support regular and retina resolution you would need to have two resources in your app bundle, 70.jpg and 70@2x.jpg with the @2x resource having both doubled with and height.
Try loading a UIImage with:
[UIImage imageNamed:@"something.png"]
It looks for an image with the specified name in the application’s main bundle. Also nice: It automatically chooses the Retina (xyz@2x.png) or non-Retina (xyz.png) version.
Your path simply wont work because your app is in a sandbox, and you are trying to use the full path.
You should be using the following instead:
UIImage *img = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"70" ofType:@"jpg"]];
or you can use, but is slower than the above:
UIImage *img = [UIImage imageNamed:@"70.jpg"];
精彩评论