I am saving the images when there is internet connection in my iphone.
Now i want to load the images which are saved in documents directory. I am getting the path, but the image is not displaying. Please help me in this.
Thanks in advance.
Here is my code:
+(UIImage *) getImagewithName:(NSString*) imagepath
{
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
UIImage *gimage=[UIImage imageWithContentsOfFile: [NSString stringWithFormat:@"%@/%@",docDir,imagepath]];
NSLog(@"%@/%@",docDir,imagepath);
return gimage;
}
+(void)DownloadImage:(NSString*)ImagePath {
if ([ImagePath isEqualToString:@""])
return;
UIImage *dimage = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http:/uploads/%@",ImagePath]]]];
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSLog(@"pathIMAGEPATHS:::::::%@",ImagePath);
NSLog(@"path:::::::%@",docDir);
NSArray *patharr=[ImagePath componentsSeparatedByString:@"."];
NSString* Ext=[NSString stringWithFormat: @"%@",[patharr objectAtIndex:1]];
NSString *FilePath = [NSString stringWithFormat: [NSString stringWithFormat:@"%@/%@",docDir,ImagePath]];
if([Ext isEqualToString:@"png"])
{
NSLog(@"saving png");
NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(dimage)];
[data1 writeToFile:FilePath atomically:YES];
}
else if([Ext isEqualToString:@"jpeg"])
{
NSLog(@"saving jpeg");
//NSString *jpegFilePath = [NSString stringWithFormat:@"%@/test.jpeg",docDir];
NSData *data2 = [NSData dataWithData:UIImageJPEGRepresentation(dimage, 1.0f)];//1.0f = 100% quality
[data2 writeToFile:FilePath atomically:YES];
}
else
{
NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(dimage)];
[data1 writeToFile:FilePath atomically:YES];
}
NSLog(@"saving image done");
[dimage release];
}
viggio24 makes a good point. But moreover, this code seems incredibly complicated to do something incredibly simple. Why do you download to data, then turn it into an image, just to turn it back into data, and finally write it? And then you read it again and make a new image? Why not just download the file to disk and read it?
UIImagewill do all the work of managing PNG and JPEG for you. Something like:This is still a horrible idea in most cases, though, since it blocks the calling thread. It’s better to do this with
NSURLDownloadwhich will do it all for you in the background and tell you when it’s done.I’d simplify the code, and then follow viggio24’s comments, making sure that you error check this stuff. You’re probably just not reading the file correctly or failing to write it.