Download an asynchronous multiple images in UITableViewView? - iphone

How can i download an asynchronous multiple images in the UITableView using ASIHttpRequest or something useful?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
..........
// Creation
UIImageView *avatar;
UILabel *content;
// Tag the IBOutlets
avatar = (UIImageView*)[cell viewWithTag:14];
content = (UILabel*)[cell.contentView viewWithTag:4];
// Field
avatar.image = image
content.text = entryReviewtableView.content;
}

No need to introduce a dependency to a whole framework such as ASIHTTPRequest just to download one image, when you can do it a few easy lines of code using GCD:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *imageDate = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];
dispatch_async(dispatch_get_main_queue(), ^{
avatar.image = image;
});
});
This is asynchronous and all the goodness. But in a few lines of code you can write, understand, bug-fix, extend and maintain yourself.

You can be use the asynchronous image view instead of the default image view. for reference you can visit tutorial Here.

UIImageView *imgV=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 1024, 748)];
ASIHTTPRequest *req=[ASIHTTPRequest requestWithURL:[NSURL URLWithString:[Array objectAtIndex:indexPath.row]]];
[req setUsername:[NSString stringWithFormat:#"%i",i]];
[req setUserInfo:[NSDictionary dictionaryWithObjectsAndKeys:imgV,#"imgV",nil]];
[req setDelegate:self];
[req startAsynchronous];
//[imgV setContentMode:UIViewContentModeScaleToFill];
[imgV setContentMode:UIViewContentModeScaleAspectFit];
//[imgV setClipsToBounds:YES];
[imgV setTag:kTagImageViewInScrollView];
[cell addSubview:imgV];
- (void)requestFinished:(ASIHTTPRequest )request {
[(UIImageView)[[request userInfo] valueForKey:#"imgV"] setImage:[UIImage imageWithData:[request responseData]]];
[(UIActivityIndicatorView*) [(UIScrollView*) [scr viewWithTag:([[request username] intValue]+1)] viewWithTag:kActTag] removeFromSuperview];
}

Related

Set UITableview cell image from url in iOS

I am setting image on UITableViewCell using image url ,but the images doesn't get load unless i scrolls the UITableView.Here is the code that i have been using,i got to know about SDWeb Image library to download images from url,but i does;t want to use any library.Please tell me what aim doing wrong in this.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
NSDictionary *dictCard=[cardsDetailsArray objectAtIndex:indexPath.row];
UILabel *nameLabel = (UILabel *)[cell viewWithTag:10];
UILabel *dateLabel = (UILabel *)[cell viewWithTag:11];
UIImageView *cellImage=(UIImageView *)[cell viewWithTag:0];
CGSize firstSize=CGSizeZero;
if([[dictCard objectForKey:#"orientation"]isEqualToString:#"1"]){
[cellImage setFrame:CGRectMake(0, 0, 75, 68)];
firstSize=CGSizeMake(75,68);
}
if([[dictCard objectForKey:#"orientation"]isEqualToString:#"0"]){
[cellImage setFrame:CGRectMake(0, 0, 107, 72)];
firstSize=CGSizeMake(107,72);
}
[cellImage setBackgroundColor:[UIColor clearColor]];
NSString *string=[dictCard objectForKey:#"email_sent"];
NSArray *items = [string componentsSeparatedByString:#","];
dateLabel.text=[dictCard objectForKey:#"date"];
nameLabel.text=[NSString stringWithFormat:#"Sent to %d People",[items count]];
NSURL* url = [NSURL URLWithString:(NSString *) [dictCard objectForKey:#"card_thumbnail"]];
NSURLRequest* request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse * response,
NSData * data,
NSError * error) {
if (!error){
UIImage* image = [[UIImage alloc] initWithData:data];
//i am scaling the image here
UIImage *imageScale=[self imageWithImage:image scaledToSize:firstSize];
[cellImage setImage:imageScale];
}
}];
return cell;
}
I have also added [__tableViewDraft reloadData];after setting the cell image but due to this my cell keeps on changing its cell image.
Once the image has been downloaded, you need to ask iOS to refresh the cell. Check out reloadRowsAtIndexPaths:withRowAnimation:, among others.
Typically you might have have cells backed by CoreData objects and download and save the image to the managed object. You'd then have an NSFetchedResultsControllerDelegate trigger an update when the managed object changes, refreshing the row.

Loading images in background to optimize the loading in ios

I am trying to optimize the load in my application, in fact, I have a lot of images that loaded in my application, and I spend a lot of time waiting for a view controller to open, especially the first initial view which includes a lot of images.
I took a look at apple sample
but I cannot re-work the whole application, what I want is just to tell me specifically what should I do?, I implement?
in the tableview, where the cell is implemented cellforrowatindexpath:
NSURL *imageURL = ......;
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *imageLoad;
imageLoad = [[UIImage alloc] initWithData:imageData];
imageView.image = imageLoad;
could I do something?
thank you for your help!
Try this code:
dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(q, ^{
/* Fetch the image from the server... */
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[UIImage alloc] initWithData:data];
dispatch_async(dispatch_get_main_queue(), ^{
/* This is the main thread again, where we set the tableView's image to
be what we just fetched. */
cell.imgview.image = img;
});
});
Yes, you can add placeholder image to it.
It will not slow down the scrolling and will load image accordingly with time.
Also import this file UIImageView+WebCache.m and MapKit Framework
Here is the link to download the files.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
UIImageview* iV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
[iV setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:#"image_placeholder.gif"]];
[cell.contentView addSubview:iV];
[iV release];
}
Just clean, build and run.
To enable the app while getting the images from server and disable block while loading the images try to use UIImageView+AFNetworking library to load the image from server asynchronously AFNetworking
NSString *imageUrl = [[dict objectForKey:#"photo"] objectForKey:#"url"];
UIImageView *myImage = [[UIImageView alloc] init];
[myImage setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:[UIImage imageNamed:#"PlaceHolder.png"]];
Just add this library and include the UIImageView+AFNetworking so you can use the new UIImageView Category imageWithUrl
Take a look at this control:
https://github.com/nicklockwood/AsyncImageView
It's very easy to implement (only 1 header file) and will suit your needs just fine.
Using this control:
Instead of declaring:
NSURL *imageURL = ......;
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *imageLoad;
imageLoad = [[UIImage alloc] initWithData:imageData];
imageView.image = imageLoad;
Use:
NSURL *imageURL = ......;
imageView.imageURL = imageURL;
you can check this tutorial on NSOperationQueue and this on GCD doing exactly same. Also you can try using:
// Block variable to be assigned in block.
__block NSData *imageData;
dispatch_queue_t backgroundQueue = dispatch_queue_create("com.razeware.imagegrabber.bgqueue", NULL);
// Dispatch a background thread for download
dispatch_async(backgroundQueue, ^(void) {
imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *imageLoad;
imageLoad = [[UIImage alloc] initWithData:imageData];
// Update UI on main thread
dispatch_async(dispatch_get_main_queue(), ^(void) {
imageView.image = imageLoad;
});
});
You can try something like this!....
dispatch_queue_t checkInQueueForPostImage = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(checkInQueueForPostImage, ^{
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:postAndCheckInDetails.postImageURL]]];
dispatch_sync(dispatch_get_main_queue(), ^{
if (image!=nil) {
[uploadImage setImage:image];
}
[cell setNeedsLayout];
});
});
Here is a slightly modified approach of Ramu Pasupoletis answer. I added the
__block
modifier to make the var img visible inside the block called on the main thread. Here is the complete method definition which I use in
-(UITableViewCell*)cellforRowAtIndexPath:(UIIndexPath*)indexPath;
for fetching the thumbnails lazily. I also added placeholders there for the cells UIImageViews.
//lazy loading of thumbnails for images in cell via bg thread
-(void)loadImageForCell:(CustomEditTableViewCell*)theCell withFilepath: (NSString*)filepath{
dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(q, ^{
UIImage (__block *img) = [UIImage imageWithContentsOfFile:filepath];
UIImage *thumbnail = [[GlobalFunctions sharedGlobalFunctions] imageOfSize:CGSizeMake(40, 40) fromImage:img];
dispatch_async(dispatch_get_main_queue(), ^{
theCell.imageView.image = thumbnail;
});
});
}
Use IDAsyncImageView.h
//////////////////////////////////////
IDAsyncImageView.h
/////////////////////////////////////
#interface IDAsyncImageView : NSObject
#property (nonatomic, strong) NSCache *cache;
+ (instancetype)instance;
- (void)loadImageView:(UIImageView*)imageView withURLString:(NSString *)urlString;
#end
//////////////////////////////////////
IDAsyncImageView.m
/////////////////////////////////////
#import "IDAsyncImageView.h"
#implementation IDAsyncImageView
+ (instancetype)instance
{
static IDAsyncImageView *_instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [[self alloc] init];
});
return _instance;
}
- (instancetype)init
{
self = [super init];
if (self) {
self.cache = [[NSCache alloc] init];
}
return self;
}
- (void)loadImageView:(UIImageView*)imageView withURLString:(NSString *)urlString
{
UIActivityIndicatorView* activityView;
activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
activityView.hidesWhenStopped = YES;
activityView.center = CGPointMake(imageView.bounds.size.width / 2.0f, imageView.bounds.size.height / 2.0f);
activityView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin;
[imageView addSubview:activityView];
[activityView startAnimating];
UIImage* imageLoad = [self.cache objectForKey:urlString];
if (nil != imageLoad) {
imageView.image = imageLoad;
[activityView removeFromSuperview];
}
else {
// Block variable to be assigned in block.
__block NSData *imageData;
// Dispatch a background thread for download
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
UIImage* imageLoad = [[UIImage alloc] initWithData:imageData];
// Update UI on main thread
dispatch_async(dispatch_get_main_queue(), ^(void) {
[self.cache setObject:imageLoad forKey:urlString];
imageView.image = imageLoad;
[activityView removeFromSuperview];
});
});
}
}
//////////////////////////////////////
ViewController.m
//////////////////////////////////////
- (void)viewDidLoad {
[super viewDidLoad];
[[IDAsyncImageView instance] loadImageView:myImageView withURLString:aUrl];
}
You can use async imageview.
- (void) loadImageFromURL:(NSURL*)url placeholderImage:(UIImage*)placeholder cachingKey:(NSString*)key {
self.imageURL = url;
self.image = placeholder;
NSData *cachedData = [FTWCache objectForKey:key];
if (cachedData) {
self.imageURL = nil;
self.image = [UIImage imageWithData:cachedData];
return;
}
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *imageFromData = [UIImage imageWithData:data];
[FTWCache setObject:data forKey:key];
if (imageFromData) {
if ([self.imageURL.absoluteString isEqualToString:url.absoluteString]) {
dispatch_sync(dispatch_get_main_queue(), ^{
self.image = imageFromData;
});
} else {
// NSLog(#"urls are not the same, bailing out!");
}
}
self.imageURL = nil;
});
}
Take a look at this link.You will have an idea on using async imageview.

ASIHttprequest Muliple request with one progressview

After the purchase is completed ,i want to donwload image, audio and video from server.
Currently i am able to download the image and can see the progress in UIProgressView but i am not sure how can we show the single UIProgressView for multiple url requests.
I would like to know whether we can show one UIProgressView for multiple url request using ASIHttpRequest.
please let me know how to proceed? and thanks a lot
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
self.request=nil;
}
return self;
}
- (void)fetchThreeImages1:(id)sender
{
[imageView1 setImage:nil];
if (!networkQueue) {
networkQueue = [[ASINetworkQueue alloc] init];
}
failed = NO;
[networkQueue reset];
[networkQueue setRequestDidFinishSelector:#selector(requestForDownloadOfFileFinished:)];
[networkQueue setRequestDidFailSelector:#selector(requestForDownloadOfFileFailed:)];
[networkQueue setShowAccurateProgress:YES];
[networkQueue setDelegate:self];
self.request=nil;
NSURL *url;
NSString *urlString=#"http://www.digitalreview.ca/cams/pics/DSCN0044.JPG";
url = [NSURL URLWithString:urlString];
request = [ASIHTTPRequest requestWithURL:url];
NSString *Filename = [urlString lastPathComponent];
[request setDownloadProgressDelegate:imageProgressIndicator1];
[request setUserInfo:[NSDictionary dictionaryWithObject:#"request1" forKey:#"name"]];
[request setDownloadDestinationPath:[[NSHomeDirectory() stringByAppendingPathComponent:#"Documents"] stringByAppendingPathComponent:Filename]];
[request setShouldContinueWhenAppEntersBackground:YES];
[request setDelegate:self];
[request setDidReceiveDataSelector:#selector(request:didReceiveBytes:)];
[request setShowAccurateProgress:YES];
[networkQueue addOperation:request];
[networkQueue go];
}
- (void)requestForDownloadOfFileFinished:(ASIHTTPRequest *)request1
{
NSLog(#"req finish.........");
NSLog(#"Content will be %llu bytes in size",[request1 contentLength]);
goButton.hidden=YES;
[imageProgressIndicator1 removeFromSuperview];
UIImage *img = [UIImage imageWithContentsOfFile:[request1 downloadDestinationPath]];
array=[[[NSMutableArray alloc]init]autorelease];
[array addObject:img];
image = [[UIImage alloc ]initWithData:[request1 responseData]];
NSString *receivedString = [request1 responseString];
NSLog(#"received string %#",receivedString);
NSData *responseData = [request1 responseData];
NSString *response = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Server response:%#", response);
NSLog(#"response data %#",[request1 responseData]);
NSLog(#"download destination path %#",[request downloadDestinationPath]);
NSLog(#"download destination path1 %#",[request1 downloadDestinationPath]);
NSLog(#"image %#",img);
NSLog(#"image1 %#",image);
if (img) {
[imageView1 setImage:img];
}
UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:#"Download" message:#"Download Completed" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil] autorelease];
[alertView show];
//completed=true;
NSLog(#"mutablearray count %#",[array objectAtIndex:0]);
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath
//-------------------------------------------------------------------------------
{
int tablePadding = 40;
int tableWidth = [self.tblViewDownload frame].size.width;
if (tableWidth > 480) {
tablePadding = 110;
}
static NSString *CellIdentifier = #"TypeCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero]autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
if([indexPath row]==0)
{
NSString *urlString=#"http://www.digitalreview.ca/cams/pics/DSCN0044.JPG";
NSString* theFileName = [urlString lastPathComponent];
NSLog(#"%# the filename",theFileName);
goButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[goButton setTitle:#"Go" forState:UIControlStateNormal];
[goButton sizeToFit];
[goButton setFrame:CGRectMake(220,30,50,30)];
[goButton addTarget:self action:#selector(fetchThreeImages1:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:goButton];
//-------------
NSString *workSpacePath=[[self applicationDocumentsDirectory] stringByAppendingPathComponent:theFileName];
NSLog(#"%# workSpacePath ",workSpacePath);
if ( workSpacePath ){
NSLog(#"%# workSpacePath ",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]];
imageView1.image = [UIImage imageWithContentsOfFile:workSpacePath];
[cell addSubview:imageView1];
NSLog(#"dfdfD");
NSLog(#"sdfdsf");
}
imageProgressIndicator1 = [[[UIProgressView alloc] initWithFrame:CGRectZero] autorelease];
[cell addSubview:imageProgressIndicator1];
}
NSUInteger imageWidth = (tableWidth-tablePadding-20)/3;
NSUInteger imageHeight = 35;
[imageView1 setFrame:CGRectMake(tablePadding/2,20,imageWidth,imageHeight)];
[imageProgressIndicator1 setFrame:CGRectMake(120,40,imageWidth,20)];
}
return cell;
}
Have a look at the ASIHTTPRequest documentation section 'Tracking download progress for a set of requests'.
You basically need to create an ASINetworkQueue and add each of your requests to it. The queue is responsible for tracking overall progress and will call delegate methods where you can update your progress bar.

UIImage not working properly?

i m trying load UIImages from server asynchronously in UITableViewCell.
My code worked fine in simulator but not on device. My code as follows,
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
IScopeCustomTableCell *cell = (IScopeCustomTableCell *)[tableView dequeueReusableCellWithIdentifier:CellClassName];
if (!cell){
NSArray *topLevelItems = [cellLoader instantiateWithOwner:self options:nil];
cell = [topLevelItems objectAtIndex:0];
}
cell.delegate = self;
cell.videoTitle.text = [[videoDataArray objectAtIndex:indexPath.row] objectForKey:#"VideoTitle"];
cell.videoLink = [[videoDataArray objectAtIndex:indexPath.row] objectForKey:#"VideoLink"];
cell.videoThumbnailImageLink = [[videoDataArray objectAtIndex:indexPath.row] objectForKey:#"VideoThumbnail"];
cell.videoThumbnail.tag = indexPath.row;
cell.tag = indexPath.row;
[cell.activityIndicator startAnimating];
NSInvocationOperation *operation = [[NSInvocationOperation alloc]
initWithTarget:self
selector:#selector(loadImage:)
object:cell];
[queue addOperation:operation];
return cell;
}
- (void)loadImage:(IScopeCustomTableCell *)cell {
NSLog(#"Image link :- %#", cell.videoThumbnailImageLink);
//NSData* imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:cell.videoThumbnailImageLink]];
NSData* imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:cell.videoThumbnailImageLink]];
UIImage* image = [UIImage imageWithData:imageData];
cell.videoThumbnail.image = image;
[cell.activityIndicator stopAnimating];
[cell.activityIndicator removeFromSuperview];
//[self performSelectorOnMainThread:#selector(displayImage:) withObject:image waitUntilDone:NO];
}
The above code fine on simulator but not on device, becoz, UIImage *image get (0X0)null in even though NSData loadImage method containing appropriate data.
What you are doing is not the best way to do it as it will create many autoreleased objects and will increase the size of your app and also you are not releasing your operation... so first of all release your operation after [queue addOperation:operation];
and use this code instead for getting the image data and storing it in your image...
NSData* data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:cell.videoThumbnailImageLink]]];
UIImage* img = [[UIImage alloc] initWithData:data];
[data release];
cell.videoThumbnail.image = image;
[img release];
hoping this sorts your problem..
This link containing image cache code and it worked properly exact that i would like.
https://github.com/jakemarsh/JMImageCache

Load image to a tableView from URL iphone sdk

I have tableView and need to load image from URL. I have an array that contains the URLs of images and when the page loads I need to load all the images into the tableview. Note that, not from a single URL, have an array with different URLs. How can I implement that? Please help
Thanks.
You can use GCD to load images in background thread, like this:
//get a dispatch queue
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:imageURL];
//this will set the image when loading is finished
dispatch_async(dispatch_get_main_queue(), ^{
imageView.image = [UIImage imageWithData:image];
});
});
Hi. But you probably need to add a dispatch_release(concurrentQueue); to be sure no leak. – Franck Aug 25 at 19:43
You can use Lazy Loading when you want to download Images from internet
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//All you reusable cell implementation here.
//Since your Images sizes differ. Keep a custom Imageview
if(![imagesForCategories containsObject:indexPath])
{
customImageView.image = [UIImage imageNamed:#"default-image.png"];
NSMutableArray *arr = [[NSArray alloc] initWithObjects:[imageUrlArray objectAtIndex:indexPath.row],indexPath, nil];
[self performSelectorInBackground:#selector(loadImageInBackground:) withObject:arr];
[arr release];
}
return cell;
}
- (void) loadImageInBackground:(NSArray *)urlAndTagReference
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSURL *imgUrl=[[NSURL alloc] initWithString:[urlAndTagReference objectAtIndex:0]];
NSData *imgData = [NSData dataWithContentsOfURL:imgUrl];
UIImage *img = [UIImage imageWithData:imgData];
[imgUrl release];
NSMutableArray *arr = [[NSMutableArray alloc ] initWithObjects:img,[urlAndTagReference objectAtIndex:1], nil ];
[self performSelectorOnMainThread:#selector(assignImageToImageView:) withObject:arr waitUntilDone:YES];
[arr release];
[pool release];
}
- (void) assignImageToImageView:(NSMutableArray *)imgAndTagReference
{
[imagesForCategories addObject:[imgAndTagReference objectAtIndex:1]];
UITableViewCell *cell = [celebCategoryTableView cellForRowAtIndexPath:[imgAndTagReference objectAtIndex:1]];
UIImageView *profilePic = (UIImageView *)[cell.contentView viewWithTag:20];
profilePic.image = [imgAndTagReference objectAtIndex:0];
}
You can use SDWebImage which permits very easy and speed loading of images in UITableView.
https://github.com/rs/SDWebImage
Try this code,imagearray contains urls of image
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSData* imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString: [imagearray objectAtIndex:row]]];
UIImage* image = [[UIImage alloc] initWithData:imageData];
cell.imageView.image =image;
return cell;
}
You need to create your custom cell for lazy loading. This will allow you to download images correctly and without freezing. Here is nice example how to do this:
Asynch image loading
With afnetworki, it is too easy.
//afnetworking
#import "UIImageView+AFNetworking.h"
[cell.iboImageView setImageWithURL:[NSURL URLWithString:server.imagen] placeholderImage:[UIImage imageNamed:#"qhacer_logo.png"]];