IPhone asynchronously loads Images
Asyncimageview. h file
@ Interface asyncimageview: uiview {
Nsurlconnection * connection;
Nsmutabledata * data;
}
@ End
Asyncimageview. M file
@ Implementation asyncimageview
-(Void) loadimagefromurl :( nsurl *) URL {
If (connection! = Nil) {[connection release];}
If (Data! = Nil) {[data release];}
Nsurlrequest * request = [nsurlrequest requestwithurl: URL
Cachepolicy: nsurlrequestuseprotocolcachepolicy
Timeoutinterval: 60.0];
Connection = [[nsurlconnection alloc]
Initwithrequest: Request delegate: Self];
// Todo error handling, what if connection is nil?
}
-(Void) connection :( nsurlconnection *) THECONNECTION
Didreceivedata :( nsdata *) incrementaldata {
If (Data = nil ){
Data =
[[Nsmutabledata alloc] initwithcapacity: 2048];
}
[Data appenddata: incrementaldata];
}
-(Void) connectiondidfinishloading :( nsurlconnection *) THECONNECTION {
[Connection release];
Connection = nil;
If ([[self subviews] Count] & gt; 0 ){
[[Self subviews] objectatindex: 0] removefromsuperview];
}
Uiimageview * imageview = [[uiimageview alloc] initwithimage: [uiimage imagewithdata: Data] autorelease];
Imageview. contentmode = uiviewcontentmodescaleaspectfit;
Imageview. autoresizingmask = (uiviewautoresizingflexiblewidth | uiviewautoresizingflexibleheight );
[Self addsubview: imageview];
Imageview. Frame = self. bounds;
[Imageview setneedslayout];
[Self setneedslayout];
[Data release];
Data = nil;
}
-(Uiimage *) image {
Uiimageview * IV = [[self subviews] objectatindex: 0];
Return [IV image];
}
-(Void) dealloc {
[Connection cancel];
[Connection release];
[Data release];
[Super dealloc];
}
@ End
Specific use in tableview
-(Uitableviewcell *) tableview :( uitableview *) tableview
Cellforrowatindexpath :( nsindexpath *) indexpath {
Static nsstring * cellidentifier = @ "imagecell ";
Uitableviewcell * cell = [tableview dequeuereusablecellwithidentifier: cellidentifier];
If (cell = nil ){
Cell = [[[uitableviewcell alloc]
Initwithframe: cgrectzero reuseidentifier: cellidentifier]
Autorelease];
} Else {
Asyncimageview * oldimage = (asyncimageview *)
[Cell. contentview viewwithtag: 999];
[Oldimage removefromsuperview];
}
Cgrect frame;
Frame. Size. width = 75; frame. Size. Height = 75;
Frame. Origin. x = 0; frame. Origin. Y = 0;
Asyncimageview * asyncimage = [[asyncimageview alloc]
Initwithframe: frame] autorelease];
Asyncimage. tag= 999;
Nsurl * url = [imagedownload
Thumbnailurlatindex: indexpath. Row];
[Asyncimage loadimagefromurl: url];
[Cell. contentview addsubview: asyncimage];
Return cell;
}