How to display a image downloaded from URL in iPhone? - iphone

I am downloading a image from the url and saving it. When i try to display the same image in UI using ImageView I am not able to do it. So please suggest what changes I need to be done in the following code.
Thank you.
{
NSLog(#"Downloading...");
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://www.objectgraph.com/images/og_logo.png"]]];
NSLog(#"%f,%f",image.size.width,image.size.height);
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSLog(#"%#",docDir);
NSLog(#"saving png::::%#", docDir);
NSString *pngFilePath = [NSString stringWithFormat:#"%#/test.png",docDir];
NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
[data1 writeToFile:pngFilePath atomically:YES];
NSString *sss = [docDir stringByAppendingString:#"/test.png"];
imageView1.image = [UIImage imageNamed:sss];
NSLog(#"------%#",sss);
[image release];
}

UIImage *theUIimage = [UIImage imageNamed:sss];
image = [[UIImageView alloc] initWithImage:theUIimage];
[imageView1 addSubview:image];

How is your imageView initalized? Make sure to also specify the imageView.frame.
e.G.:
CGRect frame = CGRectMake(xPositionInView,yPositionInView,
image.size.width,image.size.height);
imageView.frame = frame;

Related

Image is not being shown when using UIImage imageWithData:NSData dataWithContentsOfFile

The below code is not displaying the image which is downloaded from online and written into my application documents directory.
i have checked inside the iphone's simulator documents directory , the downloaded file is exist.
but the image is not displayed.
When trying to add a resources image using UIImage *imgBack = [UIImage imageNamed:#"btn-back.png"]; , the uiimageview displays the image.bu the image which is downloaded from online and stored inside the app directory is not displaying the image.
Pls let me know and thanks
NSString *workSpacePath=[[self applicationDocumentsDirectory] stringByAppendingPathComponent:theFileName];
NSLog(#"%# workSpacePath ",workSpacePath);
if ( workSpacePath ){
//--------------
UIImage *imgBack = [UIImage imageNamed:#"btn-back.png"];
imageView1 = [[[UIImageView alloc] initWithFrame:CGRectMake(0,0,20,20)] autorelease];
[imageView1 setBackgroundColor:[UIColor grayColor]];
imageView1.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:workSpacePath]];
[cell addSubview:imageView1];
}
try this ,this is perfectly working for me:
- (void)viewDidLoad
{
  [super viewDidLoad];
NSURL *url1 = [NSURL URLWithString:#"http://mobiledevelopertips.com/images/logo-iphone-dev-tips.png"];
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url1]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:#"savedImage.png"];
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:NO];
NSArray *paths1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory1 = [paths1 objectAtIndex:0];
NSString *workSpacePath = [documentsDirectory1 stringByAppendingPathComponent:#"savedImage.png"];
NSLog(#"%# workSpacePath ",workSpacePath);
if ( workSpacePath )
{
imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(20,20,20,20)];
[imageView1 setBackgroundColor:[UIColor grayColor]];
imageView1.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:workSpacePath]];
[self.view addSubview:imageView1];
}
}
Instead of first converting the file to NSData, you can use
[UIImage imageWithContentsOfFile:filePath]
directly to load a image with given path.

Download Image and UIButton BG image

I am trying to do download some images from server then , set these images as background image for some UIButtons .
so first downloading images :
NSString *urlMag1 = [NSString stringWithFormat:#"http://myweb.com/i224_mag1.png"];
NSString *urlMag2 = [NSString stringWithFormat:#"http://myweb.com/i224_mag2.png"];
NSString *str = [NSString stringWithFormat:urlMag1,urlMag2,nil];
NSData *data = [NSData dataWithContentsOfFile:str];
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
[data writeToFile:path atomically:YES];
UIImage *imgMag1 = [UIImage imageNamed:#"i224_mag2.png"];
[mag2 setBackgroundImage:imgMag1 forState:UIControlStateNormal];
but nothing happens !!,and how can I check to if these images are in directory to avoid more downloading
I would be grateful if you help me to solve this
thanks !
EDITED
#Fernando Cervantes
I created a method to set buttons BG images something like this , but I don't know why does not work !
- (UIImage *)loadImages :(NSString *)fileNames ofType:(NSString *)extension inDirectory:(NSString *)directoryPath {
[[NSFileManager defaultManager] fileExistsAtPath:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", fileNames, extension]]];
return 0;
}
and set BG images :
- (void)buttonsBGImage {
UIImage * bgMag2 = [self loadImages:#"i224_mag2" ofType:#"png" inDirectory:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]];
[mag2 setBackgroundImage:bgMag2 forState:UIControlStateNormal];
}
but actually nothing happens ! even I check the file and it's in app directory
The following approach might help you out a bit.
Save
-(void) saveFile:(NSString *)fileName ofType:(NSString *)extension fromURL:(NSString *)fileIndexPath inDirectory:(NSString *)directoryPath {
NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileIndexPath]];
[data writeToFile:[NSString stringWithFormat:#"%#/%#.%#", directoryPath, fileName, extension] atomically:YES];
}
Check
-(BOOL) checkIfFileExists:(NSString *)fileName ofType:(NSString *)extension inDirectoryPath:(NSString *)directoryPath {
bool result;
if ([[NSFileManager defaultManager] fileExistsAtPath:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", fileName, extension]]]) {
result = TRUE;
} else {
result = FALSE;
}
return result;
}
Set
UIButton * button = [[UIButton alloc] init];
UIImage * backgroundImage = [self loadImage:#"YourImageName" ofType:#"png" inDirectory:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]];
[button setImage:backgroundImage forState:UIControlStateNormal];
-Edited-
I believe your problem is that you are returning 0 in your loadImages method. Instead of returning the image itself.
This is how I accomplished it:
Load
-(UIImage *) loadImage:(NSString *)fileName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath {
UIImage * result = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:#"%#/%#.%#", directoryPath, fileName, extension]];
return result;
}
[UIImage imageNamed:#"i224_mag2.png"]; // it is only for bundle. You should use
[UIImage imageWithContentsOfFile:path]
or
[UIImage imageWithData:data];
Update:
I use category for UIButton class.
- (void)loadImage:(NSString *)URL withActivityIndicator:(BOOL)hasActivity refreshObject:(UIView *)refresh{
// load image from cache cutted
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//this will start the image loading in bg
dispatch_async(concurrentQueue, ^{
NSData *image = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:URL]];
//this will set the image when loading is finished
dispatch_async(dispatch_get_main_queue(), ^{
UIImage *loadedImage = [UIImage imageWithData:image];
// add image to cache cutted
[self setImage:loadedImage forState:UIControlStateNormal];
});
});
}
You are making NSData using dataWithContentsOfFile: API. you should use dataWithContentsOfURL instead.
NSString *urlMag1 = [NSString stringWithFormat:#"http://myweb.com/i224_mag1.png"];
NSString *urlMag2 = [NSString stringWithFormat:#"http://myweb.com/i224_mag2.png"];
NSData *image1 = [NSdata contentsOfURL:[NSURL URLWithString:urlMag1]];
NSData *image2 = [NSdata contentsOfURL:[NSURL URLWithString:urlMag2]];
[mag2 setBackgroundImage:imgMag1 forState:UIControlStateNormal];
Usually [NSdata contentsOfURL:[NSURL URLWithString:urlMag1]]; will freeze UI until image downloading complete.

image cache iphone

this is a part of my code. I'm using a asyncImageView .Everything work good. But now i want to save in the iphone all images in a path. I know i have to use NSFileManager but where?
EDIT: now i try with my code but nothing save when i compile on my iphone
// Configure the cell.
NSDictionary *dico = [self.pseudoOnline objectAtIndex:indexPath.row];
cell.pseudo.text = [dico objectForKey:#"pseudo"];
cell.sexe.text = [dico objectForKey:#"sexe"];
cell.age.text = [dico objectForKey:#"age"];
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[dico objectForKey:#"photo"]]]];
NSString *deskTopDir = #"/Users/***/Desktop/imagesOnline";
NSString *nomPhoto = [[cell.pseudo text]stringByReplacingOccurrencesOfString:#"\n" withString:#""];;
NSLog(#"pseudo%#",nomPhoto);
NSString *jpegFilePath = [NSString stringWithFormat:#"%#/%#.jpeg",deskTopDir,nomPhoto];
NSData *data2 = [NSData dataWithData:UIImageJPEGRepresentation(image, 0.5f)]; quality
[data2 writeToFile:jpegFilePath atomically:YES];
NSLog(#"image %#",jpegFilePath);
[image release];
CGRect frame;
frame.size.width=45; frame.size.height=43;
frame.origin.x=-5; frame.origin.y=0;
asyncImageView *asyncImage = [[[asyncImageView alloc] initWithFrame:frame] autorelease];
asyncImage.tag =999;
[asyncImage loadImageFromURL:[NSURL URLWithString:[dico objectForKey:#"photo"]]];
[cell.contentView addSubview:asyncImage];
return cell;
so now it works i can download all the pictures. But now i want to load them
I'm not sure what asyncImageView is, but it appears to get an image.
If it gets the image the way your code implies, you can put your NSFileManger method call right after:
[cell.contentView addSubview:asyncImage];
If, on the other hand, the asyncImageView fetches the image asynchronously (as it's name implies), then you should put your NSFileManager method call in asyncImageView's callback delegate.
Basically, as soon as you actually have the image, you can save the image.

When to release UIImage and NSString Resources

I'm trying to get my memory management right and in the code below, if I include the final release statement (the one for filePath), it crashes and I can't see why. I've alloc'ed it, so why shouldn't I release it?
Further down, I return cellAbout to the TableView.
Can someone explain?
UIImageView *imageView = (UIImageView *)[cellAbout viewWithTag:2];
NSString *filePath = [[NSString alloc] initWithString:self.gem.poiType];
filePath = [filePath stringByAppendingString:#".png"];
UIImage *image = [[UIImage alloc] initWithContentsOfFile: filePath];
imageView.image = image;
[image release];
[filePath release];
Many thanks,
Chris.
The answer is that the original filePath string IS alloced and needs to be released, but when you have the line:
filePath = [filePath stringByAppendingString:#".png"];
you create a different string - the original pointer to filePath is now gone and is a leak.
Here is the code you actually want
NSString *filePath = self.gem.poiType;
filePath = [filePath stringByAppendingPathExtension:#"png"];
UIImage *image = [[UIImage alloc] initWithContentsOfFile: filePath];
imageView.image = image;
[image release];
So you don't need to release the filePath - it is auto released. Also apple has a special call for adding path extensions.
NSString *filePath = [self.gem.poiType stringByAppendingPathExtension:#"png"];
is actually how most people would write that code - one fewer lines.
Your Issues
UIImageView *imageView = (UIImageView *)[cellAbout viewWithTag:2];
NSString *filePath = [[NSString alloc] initWithString:self.gem.poiType];
Leaking filePath after this line.
filePath = [filePath stringByAppendingString:#".png"];
UIImage *image = [[UIImage alloc] initWithContentsOfFile: filePath];
imageView.image = image;
[image release];
Releasing an autoreleased object after this line.
[filePath release];
Instead
UIImageView *imageView = (UIImageView *)[cellAbout viewWithTag:2];
NSString *filePath = [[NSString alloc] initWithString:self.gem.poiType];
NSString *extendedFilePath = [filePath stringByAppendingString:#".png"];
[filePath release];
UIImage *image = [[UIImage alloc] initWithContentsOfFile: extendedFilePath];
imageView.image = image;
[image release];
[NSString stringByAppendingString] returns a NEW string, so that's where you're leaking your old one.
And then filePath is no longer owned by you, so when you release it later, you crash.
You could sidestep this whole thing like this:
NSString *filePath = [NSString stringWithFormat:#"%#.png",self.gem.poiType];// don't release me.
You are leaking here and later releasing an autoreleased string:
filePath = [filePath stringByAppendingString:#".png"];
If you really want to manually release, save the pointer:
NSString *filePath = [[NSString alloc] initWithString:self.gem.poiType];
NSString *somestring = [filePath stringByAppendingString:#".png"];
[filePath release];

Xcode iPhone Programming: Loading a jpg into a UIImageView from URL

My app has to load an image from a http server and displaying it into an UIImageView
How can i do that??
I tried this:
NSString *temp = [NSString alloc];
[temp stringwithString:#"http://192.168.1.2x0/pic/LC.jpg"]
temp=[(NSString *)CFURLCreateStringByAddingPercentEscapes(
nil,
(CFStringRef)temp,
NULL,
NULL,
kCFStringEncodingUTF8)
autorelease];
NSData *dato = [NSData alloc];
dato=[NSData dataWithContentsOfURL:[NSURL URLWithString:temp]];
pic = [pic initWithImage:[UIImage imageWithData:dato]];
This code is in viewdidload of the view but nothing is displayed!
The server is working because i can load xml files from it. but i can't display that image!
I need to load the image programmatically because it has to change depending on the parameter passed!
Thank you in advance.
Antonio
It should be:
NSURL * imageURL = [NSURL URLWithString:#"http://192.168.1.2x0/pic/LC.jpg"];
NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage * image = [UIImage imageWithData:imageData];
Once you have the image variable, you can throw it into a UIImageView via it's image property, ie:
myImageView.image = image;
//OR
[myImageView setImage:image];
If you need to escape special characters in your original string, you can do:
NSString * urlString = [#"http://192.168.1.2x0/pic/LC.jpg" stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSURL * imageURL = [NSURL URLWithString:urlString];
....
If you're creating your UIImageView programmatically, you do:
UIImageView * myImageView = [[UIImageView alloc] initWithImage:image];
[someOtherView addSubview:myImageView];
[myImageView release];
And because loading image from URL takes ages, it would be better to load it asynchronously. The following guide made it stupid-simple for me:
http://www.switchonthecode.com/tutorials/loading-images-asynchronously-on-iphone-using-nsinvocationoperation
Try this
NSURL *url = [NSURL URLWithString:#"http://192.168.1.2x0/pic/LC.jpg"];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImageView *subview = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f,320.0f, 460.0f)];
[subview setImage:[UIImage imageWithData:data]];
[cell addSubview:subview];
[subview release];
All the Best.
This is the actual code.
UIImageView *myview=[[UIImageView alloc]init];
myview.frame = CGRectMake(0, 0, 320, 480);
NSURL *imgURL=[[NSURL alloc]initWithString:#"http://soccerlens.com/files/2011/03/chelsea-1112-home.png"];
NSData *imgdata=[[NSData alloc]initWithContentsOfURL:imgURL];
UIImage *image=[[UIImage alloc]initWithData:imgdata];
myview.image=image;
[self.view addSubview:myview];
You should load the image in the background or the view will freeze.
Try this:
UIImage *img = [[UIImage alloc] init];
dispatch_async(dispatch_get_global_queue(0,0), ^{
NSData * data = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString:#"http://www.test.com/test.png"];
img = [UIImage imageWithData: data];
dispatch_async(dispatch_get_main_queue(), ^{
//PUT THE img INTO THE UIImageView (imgView for example)
imgView.image = img;
});
});