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
本文介绍了一个简单的图标下载器的实现方法。该下载器使用Objective-C编写,通过NSURLConnection进行网络请求来下载图标,并实现了开始和取消下载的功能。文章详细展示了如何处理下载过程中的数据接收、错误处理及完成后的操作。
1289

被折叠的 条评论
为什么被折叠?



