#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];
}