iOS经典讲解之异步加载图片类的封装

</pre><pre name="code" class="objc">//
//  ImageDownloader.h
//  LessonImageDownLoader-01

#import <Foundation/Foundation.h>

// 声明一个协议
@protocol ImageDownlodaerDelegate <NSObject>

// 成功返回数据
- (void)imageDownSucceedWithData:(NSData *)data;

// 失败返回错误信息
- (void)imageDownFailedWithData:(NSError *)error;

@end

@interface ImageDownloader : NSObject

// 声明一个代理属性
@property (nonatomic, assign) id<ImageDownlodaerDelegate> delegate;

// 声明初始化方法
- (instancetype)initWithImageUl:(NSString *)imageUrl delegate:(id<ImageDownlodaerDelegate>)delegate;

- (void)start;
- (void)cancel;

@end

#import "ImageDownloader.h"

// 没有延展 添加一个
@interface ImageDownloader () <NSURLConnectionDelegate, NSURLConnectionDataDelegate>

// 声明一个可变data 接收数据
@property (nonatomic, retain) NSMutableData *data;
//声明连接 便于访问
@property (nonatomic, retain) NSURLConnection *connection;

@end

@implementation ImageDownloader

-(void)dealloc
{
    // 终止请求最好写在控制器里 
   // [_connection cancel];
    [_data release];
    [_connection release];
    [super dealloc];
}


- (instancetype)initWithImageUl:(NSString *)imageUrl delegate:(id<ImageDownlodaerDelegate>)delegate
{
    self = [super init];
    if (self) {
        // 设置代理
        _delegate = delegate;
        
        
        //进行图片请求
        // 创建URL对象
        NSURL *url = [NSURL URLWithString:imageUrl];
        // 创建一个请求
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:30];
        // 创建一个连接 用代理方法
        self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
        // 开启连接
        // 最好是用这个类的对象去控制开始或者终止 增加灵活性
      //  [self.connection start];
    }
    return self;
}

#pragma mark -- 代理方法 --

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // 初始化data
    self.data = [NSMutableData data];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.data appendData:data];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // 加载完成 使用代理 把data传给控制器(因为imageView在控制器创建的)
    // 外面设置代理了 并且实现了协议中的方法 才让代理去
    if (_delegate != nil && [_delegate respondsToSelector:@selector(imageDownSucceedWithData:)]) {
        
        [_delegate imageDownSucceedWithData:self.data];
    }
    
    
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    if (_delegate != nil && [_delegate respondsToSelector:@selector(imageDownFailedWithData:)]) {
        [_delegate imageDownFailedWithData:error];
    }
}

-(void)start
{
    [self.connection start];
}

-(void)cancel
{
    [self.connection cancel];
}


@end




你可能感兴趣的:(ios,封装,异步加载图片)