Thursday, May 9, 2013

Asynchronous Load Image in UiTableView Cell

In this Example i will show how to load image from url Asynchronously which reduce load time.

There are two Method
Now Let Start.

I think there is no need to tell how to take TableView, just start with UiTableViewCell code.
Method 1. .h
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>

@property (retain, nonatomic) IBOutlet UITableView *tblview;
@property(retain,nonatomic)NSArray *aryImageUrl;
@end

.m
- (void)viewDidLoad

{

[super viewDidLoad];
 self.aryImageUrl =[NSArray arrayWithObjects:@"url1",@"url2",@"url3",@"url4",@"url5", nil];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.aryImageUrl count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *str=@"cell";
    
    UITableViewCell *celltbl=[tableView dequeueReusableCellWithIdentifier:str];
    if(celltbl==nil)
    {
        celltbl=[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str] autorelease];
    }
    
    NSURL *url=[NSURL URLWithString:[self.aryImageUrl objectAtIndex:[indexPath row]]];
    NSURLRequest *req=[NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *err) {
        celltbl.imageView.image=[UIImage imageWithData:data];
    }];
    
    return celltbl;
    
}

Explanation:
NSURLRequest  : NSURLRequest objects represent a URL load request in a manner independent of protocol and URL scheme.


NSURLConnection :An NSURLConnection object provides support to perform the loading of a URL request. The interface for NSURLConnection is sparse, providing only the controls to start and cancel asynchronous loads of a URL request.


sendAsynchronousRequest :

Loads the data for a URL request and executes a handler block on an operation queue when the request completes or fails.
If the request completes successfully, the data parameter of the handler block contains the resource data, and the error parameter is nil. If the request fails, the data parameter is nil and the error parameter contain information about the failure.

Parameters:
request
The URL request to load. The request object is deep-copied as part of the initialization process. Changes made to request after this method returns do not affect the request that is used for the loading process.
queue
The operation queue to which the handler block is dispatched when the request completes or failed.
handler
The handler block to execute.

Method 2.
In this method i have used class method for asychronous call.

.h
#import <Foundation/Foundation.h>
@interface WebImageOperation : NSObject
+(void)processImageWithUrlString:(NSString *)urlString andBlock:(void(^)(NSData * imageData))processImage;

@end

.m 

#import "WebImageOperation.h"
#import <Foundation/Foundation.h>
#import <QuartzCore/QuartzCore.h>
@implementation WebImageOperation
+(void)processImageWithUrlString:(NSString *)urlString andBlock:(void(^)(NSData * imageData))processImage
{

    NSURL *url=[NSURL URLWithString:urlString];
    dispatch_queue_t callerQuere=dispatch_get_current_queue();
    dispatch_queue_t downloadQueue=dispatch_queue_create("com.dresscodefinder.processimagequeue", NULL);
    dispatch_async(downloadQueue, ^{
        NSData *imageData=[NSData dataWithContentsOfURL:url];
       dispatch_async(callerQuere, ^{
           processImage(imageData);
       });
    });

    dispatch_release(downloadQueue);
}
@end


dispatch_queue_t: A dispatch queue is a lightweight object to which your application submits blocks for subsequent execution.

dispatch_async:Submits a block for asynchronous execution on a dispatch queue and returns immediately

Now in tableview call this class method inside cellForRowAtIndexPath

[WebImageOperation processImageWithUrlString:info.imageCache andBlock:^(NSData *imageData) {
        UIImage *image=[UIImage imageWithData:imageData];
        cell.imageView.image=image;
     
    }];



1 comment:

  1. You can find an example for loading image asynchronously on UITableviewCell here

    https://github.com/obyadur-rahman/Who-s-Who

    ReplyDelete