您的位置:首页 > 理论基础 > 计算机网络

iphone:使用NSURLConnection下载网络图片

2012-03-31 17:54 399 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: