iphone:使用NSURLConnection下载网络图片

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值