ITeye博客

iPhone快速参考:http下载图片示例

tiger888 · 2011-03-28 22:53 · 02-手机开发 · 移动开发 · Markdown

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

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。