IOS巅峰之图片异步下载

本文详细介绍了如何使用NSURLConnection在iOS应用中实现网络请求,包括创建请求、发送请求、处理响应和错误情况的处理。通过实例演示了从URL获取数据的基本流程,并展示了如何将数据传递给控制器进行进一步处理。
- (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;




评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值