from: http://www.iblue.cc/2011/04/使用nsurlconnection下载网络图片/
这是一个很基本的demo,直接看代码,你应该可以看得懂。
IconDownloader.h
===============================
@interface IconDownloader : NSObject
{
NSString *imageURLString;
NSMutableData *activeDownload;
NSURLConnection *imageConnection;
}
@property (nonatomic, retain) NSString *imageURLString;
@property (nonatomic, retain) NSMutableData *activeDownload;
@property (nonatomic, retain) NSURLConnection *imageConnection;
- (void)startDownload;
- (void)cancelDownload;
@end
IconDownloader.m
=====================================
#import "IconDownloader.h"
@implementation IconDownloader
@synthesize activeDownload;
@synthesize imageConnection;
#pragma mark
- (void)dealloc
{
[activeDownload release];
[imageConnection cancel];
[imageConnection release];
[super dealloc];
}
- (void)startDownload
{
self.activeDownload = [NSMutableData data];
// alloc+init and start an NSURLConnection; release on completion/failure
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:
[NSURLRequest requestWithURL:
[NSURL URLWithString:imageURLString]] delegate:self];
self.imageConnection = conn;
[conn release];
}
- (void)cancelDownload
{
[self.imageConnection cancel];
self.imageConnection = nil;
self.activeDownload = nil;
}
#pragma mark -
#pragma mark Download support (NSURLConnectionDelegate)
//每次成功请求到数据后将调下此方法
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
//把每次得到的数据依次放到数组中,这里还可以自己做一些进度条相关的效果
[self.activeDownload appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
// Clear the activeDownload property to allow later attempts
self.activeDownload = nil;
// Release the connection now that it's finished
self.imageConnection = nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// Set appIcon and clear temporary data/image
UIImage *image = [[UIImage alloc] initWithData:self.activeDownload];
self.activeDownload = nil;
[image release];
// Release the connection now that it's finished
self.imageConnection = nil;
}
@end