I have write a little class to perform the download of the images by using an NSURLConnection. The idea it's to delegate the download to this class to avoid to block the execution.
So I pass the target UIImageView (by ref) and the url to the function and start the download:
-(void)getImage:(UIImageView**)image formUrl:(NSString*)urlStr
{
NSLog(@"Downloader.getImage.url.debug: %@",urlStr);
NSURL *url = [NSURL URLWithString:urlStr];
NSURLRequest *req = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:5.0];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
NSURLConnection *c = [[NSURLConnection alloc] initWithRequest:req delegate:self];
[conn addObject:c];
int i = [conn indexOfObject:c];
[imgs insertObject:*image atIndex:i];
[c release];
}
When it's finished set the image and update the imageView:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
int i = [conn indexOfObject:connection];
NSData *rawData = [buffer objectAtIndex:i];
UIImage *img = [UIImage imageWithData:rawData];
UIImageView *imgView = [imgs objectAtIndex:i];
imgView.image = img;
[imgView setNeedsDisplay];
[conn removeObjectAtIndex:i];
[imgs removeObjectAtIndex:i];
[buffer removeObjectAtIndex:i];
if ([conn count]==0) {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}
}
This system works quite good, but i can't get updated the UIImageView inside the cells of a UITableViewCell, any idea ? (actually the cell it's updated when I click on it) There is a better way to implement this functionality ? (actually the need are: non-blocking, caching system)
Cesar
For async image loading, caching and threaded operation, I use SDImageCache class from http://github.com/rs/SDWebImage. I also wrote my own several times, but this one is brilliant and I've thrown all my old code away.
From its documentation:
Hilton
Use SDWebImage simply. I'm also using that one. Loading images smoothy. Am using below code to show the image from URL
Success part will display the image from webService. And, if there's any image failed to load or anyother failure issue you can load your own image there simply. There are more functionalities with that example. You can just refer it.
Simply follow the steps:
Click here to Download the SDWebImage
Thats its... you have done!!!
Have you tried using [tableView reloadData]; Call it at the end of connectionDidFinishLoading method