---
title: "iPhone快速参考：http下载图片示例"
author: "tiger888"
date: "2011-03-28T22:53:40Z"
tags: []
categories: ["移动开发"]
slug: "iphone-http"
draft: false
lastmod: "2011-03-28T22:54:17Z"
id: 977998
url: "https://tiger888.iteye.com/blog/977998"
---

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