IOS巅峰之图片异步下载

来源:互联网 发布:天泽网络 编辑:程序博客网 时间:2024/05/01 02:53
- (void)dealloc
{
// 终止请求, 最好写在控制器里
    [_connection release];
    [_data release];
    [super dealloc];
    

}

- (id)initWithImageUrl:(NSString *)imageUrl delegate:(id<ImageDownloaderDelegate>)delegate
{

    self = [super init];
    if (self) {
        // 进行图片的请求
        // 1.创建一个NSURL对象
        NSURL *url = [NSURL URLWithString:imageUrl];
        // 2.用NSURL对象创建一个请求
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:30.0];
        // 3.创建一个链接, 使用代理方法
        self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
        // 4.开启链接
       // [_connection start];
        // 最好是用这个对象, 可以控制开始或者终止
    }

    return self;

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{

    // 加载完成, 使用代理, 把data传给控制器(因为imageView在控制器创建的)
    // 外面设置代理, 并且实现了协议中的方法
    // 才能让代理去干活
    if (_delegate != nil &&[_delegate respondsToSelector:@selector(imageDownSuccessWithData:)]) {
        [_delegate imageDownSuccessWithData:_data];
    }

}

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

}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    self.data = [[[NSMutableData alloc] init] autorelease];
    

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{

    
    if (_delegate != nil && [_delegate respondsToSelector:@selector(imageDownFailWithData:)]) {
        [_delegate imageDownFailWithData:error];
    }



}



.h

// 成功的
- (void)imageDownSuccessWithData:(NSData  *)data;
// 失败的
- (void)imageDownFailWithData:(NSError *)error;

@end

@interface ImageDownZuoYe : NSObject<NSURLConnectionDelegate, NSURLConnectionDataDelegate>

@property (nonatomic, retain)NSURLConnection *connection;
// 声明一个代理属性
@property (nonatomic, retain)id<ImageDownloaderDelegate>delegate;

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

@property (nonatomic, retain)NSMutableData *data;

// 先声明一个初始化方法
- (id)initWithImageUrl:(NSString *)imageUrl delegate:(id<ImageDownloaderDelegate>) delegate;




0 0
原创粉丝点击