`

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

 
阅读更多

 

IconDownloader.h

===============================

@interface IconDownloader : NSObject

{

    NSString *imageURLString;

    NSMutableData *activeDownload;

    NSURLConnection *imageConnection;

}


@property
 (nonatomicretain) 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
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics