I'm fairly new to iPhone development and trying to fetch 'Images from Server' in my application.
I'm using the following method to do this:
- (UIImage *)imageFromURLString:(NSString *)urlString
{
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:@"GET"];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *result = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:&error];
[request release];
[self handleError:error];
UIImage *resultImage = [UIImage imageWithData:(NSData *)result];
NSLog(@"urlString: %@",urlString);
return resultImage;
}
This function does not return the expected image although I can see in debugger that NSData for the Image object has some value (in bytes)
Although, a very similar function for getting text from server works and I get expected values.
- (NSString *)jsonFromURLString:(NSString *)urlString
{
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:@"GET"];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *result = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:&error];
[request release];
[self handleError:error];
NSString *resultString = [[NSString alloc] initWithData:result
encoding:NSUTF8StringEncoding];
return [resultString autorelease];
}
This method works fine.
Could someone please help me in understanding why I'm not getting the Image from server?
Thanks
Therefore, an image URL is a web address that specifies the location of an image. Having an image URL makes it easy to share. In particular, it simplifies the process because recipients don't have to download it.
If all you are trying to do is grab an image from a web server via a URL there is an easier way.
This is what I use:
UIImage* myImage = [UIImage imageWithData:
[NSData dataWithContentsOfURL:
[NSURL URLWithString: @"http://example.com/image.jpg"]]];
And if you want to use it on an image view just do the following:
// Let's assume the picture is an instantiated UIImageView
[picture setImage: myImage];
[myImage release];
I'm sure there are reasons why a person might not want to use this approach, but I would start with this and see if it will do what you need it to.
I've written RemoteImage class to load images over the network asynchronously. It also takes care of freeing the memory when necessary. See this post: http://www.dimzzy.com/blog/2009/11/remote-image-for-iphone/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With