I need to check if an image exists in the project navigator. If it doesn’t it needs to download it from the internet. The goal is to be able to use images like [UIImage imageNamed:@”23451.jpg”];
So I need to check if the image exists, if not download it. I tried to do this as followed:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//Set image
NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:@"12345.jpg"];
//Check if the image exists at a given path
BOOL imageExists = [[NSFileManager defaultManager] fileExistsAtPath:imagePath];
//If the image doesn't exists download it.
if (!imageExists)
{
NSData* data = UIImageJPEGRepresentation([UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"www.mywebsite.com/12345.jpg"]]]);
[data writeToFile:imagePath atomically:YES];
}
If everything goes the right way the image is saved at the above path. But I still am not able to use this image with
[UIImage imageNamed:@"12345.jpg"];
I have got the feeling that i’m saving the images in a different directory than I should be saving them to.
Do you have any idea on how I should do this?
imageNamedwill only work form image in the app bundle, not those stored in the Document directory. And you can’t add the image to the app bundle, it readonly.There is no need to do this, you are now JPG a JPG: