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

{

    [activeDownloadrelease];

    

    [imageConnectioncancel];

    [imageConnectionrelease];

    

    [superdealloc];

}


- (void)startDownload

{

   self.activeDownload = [NSMutableDatadata];

    

   // alloc+init and start an NSURLConnection; release on completion/failure

   NSURLConnection *conn = [[NSURLConnectionalloc] initWithRequest:

                             [NSURLRequestrequestWithURL:

                              [NSURLURLWithString:imageURLString]]delegate:self];

   self.imageConnection = conn;

    [conn release];

}


- (void)cancelDownload

{

    [self.imageConnectioncancel];

   self.imageConnection =nil;

   self.activeDownload =nil;

}


#pragma mark -

#pragma mark Download support (NSURLConnectionDelegate)

//每次成功请求到数据后将调下此方法

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

    //把每次得到的数据依次放到数组中,这里还可以自己做一些进度条相关的效果

    [self.activeDownloadappendData: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


你可能感兴趣的:(image,网络,iPhone,download,interface)