I have a UITableView which contain several cell. When I click a cell, I push an other controller which shows the detail of this cell. In the detail I have a scrollView which contains several UIImageViews
. I would like to download the images for these views from the web using ASIHTTPRequest, when the detail view is loaded.
You can override UIView
. Each view has an ASIHTTPRequest
. When each download has finished, you can use drawRect
to draw the downloaded image.
this is a demo:
MyImageView.h
#import <UIKit/UIKit.h>
#import "ASIHTTPRequest.h"
@interface MyImageView : UIView <ASIHTTPRequestDelegate>
{
ASIHTTPRequest *httpRequest;
UIImage *image;
}
- (void)startRequest:(NSString *)_url;
@end
MyImageView.m
#import "MyImageView.h"
@implementation MyImageView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
[super drawRect:rect];
// Drawing code
if (image != nil) {
[image drawInRect:self.bounds];
}
}
- (void)dealloc
{
[httpRequest clearDelegatesAndCancel];
[httpRequest release];
[image release];
[super dealloc];
}
-(void)startRequest:(NSString *)_url
{
if (httpRequest != nil) {
[httpRequest clearDelegatesAndCancel];
[httpRequest release];
}
httpRequest = [[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:_url]];
[httpRequest setTimeOutSeconds:30];
[httpRequest setDelegate:self];
[httpRequest startAsynchronous];
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
if ([request responseStatusCode] == 200) {
image = [[UIImage alloc] initWithData:[request responseData]];
[self setNeedsDisplay];
}
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSLog(@"request failed");
}
Usage:
MyImageView *imageView = [[MyImageView alloc] initWithFrame:CGRectMake(100, 100, 50, 50)];
[imageView startRequest:@"http://imageUrl"];
[self.view addSubview:imageView];
[imageView release];