网络连接无论是同步还是异步,其图片的下载都是同步下载,比较卡顿,故此采用异步连接是非常有必要的
一、图?下载是iOS开发中常?的功能,但系统并未提供图?下载类。
为了便于后续使?,可以将图?下载封装到?个类?? (ImageDownloader)。 ImageDownloader 允许外界指定URL,提供开始下载和取消下载功能,并提供delegate或block将图?传递给外界。
二、代理方式的异步下载
下面直接上代码段,在.h 文件中声明协议,并设置代理
#import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @class ImageDownloader; @protocol ImageDownloaderDelegate <NSObject> @optional - (void)imageDownloader:(ImageDownloader *)imageDownloader successDownloadImage:(UIImage *)image; - (void)imageDownloader:(ImageDownloader *)imageDownloader didFailWirhError:(NSError *)error; @end @interface ImageDownloader : NSObject // 需要外界提供网址 - (instancetype)initWithURLStr:(NSString *)urlstr delegate:(id<ImageDownloaderDelegate>)delegate; // 遍历构造器,方便外界使用 + (ImageDownloader *)imageDownloaderWithURLStr:(NSString *)urlStr delegate:(id<ImageDownloaderDelegate>)delegate; @end
在 .m 文件中
#import "ImageDownloader.h" @interface ImageDownloader ()<NSURLConnectionDataDelegate>{ id<ImageDownloaderDelegate>_delegate;// 定义实例变量,目的是为了在其他方法中使用_delegate } @property(nonatomic, retain)NSMutableData *receivedData; @end @implementation ImageDownloader - (void)dealloc { [_receivedData release]; [super dealloc]; } - (NSMutableData *)receivedData{ if (_receivedData == nil) { self.receivedData = [NSMutableData dataWithCapacity:0]; } return _receivedData; } - (instancetype)initWithURLStr:(NSString *)urlstr delegate:(id<ImageDownloaderDelegate>)delegate{ self = [super init]; if (self) { NSURL *url = [NSURL URLWithString:urlstr]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease] ; _delegate = delegate; } return self; } + (ImageDownloader *)imageDownloaderWithURLStr:(NSString *)urlStr delegate:(id<ImageDownloaderDelegate>)delegate{ ImageDownloader *imageDownloader = [[[ImageDownloader alloc] initWithURLStr:urlStr delegate:delegate] autorelease]; return imageDownloader; } - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ [self.receivedData appendData:data]; } - (void)connectionDidFinishLoading:(NSURLConnection *)connection{ if (_delegate && [_delegate respondsToSelector:@selector(imageDownloader: successDownloadImage: )]) { UIImage *image = [UIImage imageWithData:self.receivedData]; [_delegate imageDownloader:self successDownloadImage:image]; } } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{ if (_delegate && [_delegate respondsToSelector:@selector(imageDownloader:didFailWirhError:)]) { NSError *error = nil; [_delegate imageDownloader:self didFailWirhError:error]; } } @end
这样一来我们就可以在外界使用这个类,来实现图片的异步下载功能。
原文:http://www.cnblogs.com/qiushifalife/p/4803002.html