HTTP_WebImageView类(自定义封装下载图片类)


#import "WebImageView.h"


@interface WebImageView ()<NSURLConnectionDataDelegate,NSURLConnectionDelegate>

{

    //保存当前图片对象要显示的图片资源

    NSURL *_url;

    //显示加载状态

    UILabel *_label;

    //保存下载好的图片数据

    NSMutableData *_data;

}

@end


@implementation WebImageView


- (void)setImageWithUrlString:(NSString *)urlString

{

    //第一步,通过同步下载数据从本地缓存数据

    //1.创建url

    //1.1给字符串添加百分号的转义字符(为防止url中出现中文字符)

    //没有中文字符的url不要重新编码,不然会出现参数错误

    NSString *urlStr = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    //1.2创建nsurl

    _url = [NSURL URLWithString:urlStr];

    

    //2.1创建请求数据对象并设置请求数据方式

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:_urlcachePolicy:NSURLRequestReturnCacheDataDontLoad timeoutInterval:0];

    //2.2创建保存响应包对象

    NSURLResponse *response = nil;

    //2.3创建发生连接错误的保存对象

    NSError *error = nil;

    //2.4创建保存请求数据的对象

    NSData *data = nil;

    //调用nsurlconnection方法开始同步请求数据

    data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

    //判断请求结果

    //本地已经有数据

    if (error == nil) { 

        self.image = [UIImage imageWithData:data];

        return;

    }

    //第二步,当本地没有缓存数据则异步从网络下载数据

    if (_data == nil) {

        _data = [NSMutableData data];

    }else{

        [_data setLength:0];

    }

    //初始化label标签

    if (_label == nil) {

        

        _label = [[UILabel alloc]initWithFrame:self.bounds];

        

        [self addSubview:_label];

    }

    

    //设置label的默认显示文字

    _label.text = @"努力加载中...";

    //重新设置请求对象的请求数据方式

    [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];

    //重新设置超时时间

    [request setTimeoutInterval:30];

    //创建连接对象实例并设置代理对象和初始化

    NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:NO];

    //调用连接对象开始异步下载

    [conn start];

 

}


#pragma mark-nsurlconnection协议方法

//当发生响应错误时调用方法

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

{

    _label.text = @"网络不给力";

}

//当接收到响应数据包时调用方法

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{

    //清空数据

    [_data setLength:0];

}

//当接收到数据时调用方法

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

    [_data appendData:data];

}

//当接收完数据后调用方法

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{

    self.image = [UIImage imageWithData:_data];

    //成功下载数据后删除提示信息控件

    [_label removeFromSuperview];

}

@end

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值