iOS异步请求下载图片

在iOS中可以这样获取一张网络图片

NSURL *url = [NSURL URLWithString:@"http://f.hiphotos.baidu.com/image/w%3D2048/sign=91c1063e1f950a7b753549c43ee963d9/f31fbe096b63f624b6a9640b8544ebf81b4ca3c6.jpg"];

NSData *data = [[NSData alloc] initWithContentsOfURL:url];

UIImage *img = [UIImage imageWithData:data];

但是图片比较大的时候程序会卡在这里,所以我们要用异步请求来下载图片

1.新建一个single view工程

2.ViewController.h文件:

@interface ViewController : UIViewController {

NSMutableData* _imageData;//如果图片比较大的话,response会分几次返回相应数据,所以需要用NSMutableData来接受数据

float _length;

}

@end

3.ViewController.m文件:

- (void)viewDidLoad

{

[super viewDidLoad];

//初始化图片数据

_imageData = [[NSMutableData alloc] init];

//请求

NSURL *url = [NSURL URLWithString:@"http://f.hiphotos.baidu.com/image/w%3D2048/sign=91c1063e1f950a7b753549c43ee963d9/f31fbe096b63f624b6a9640b8544ebf81b4ca3c6.jpg"];

NSURLRequest *request = [NSURLRequest requestWithURL:url];

//连接

[NSURLConnection connectionWithRequest:request delegate:self];

}

4.接受响应头和响应体

//响应头

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

{

//清空图片数据

[_imageData setLength:0];

//强制转换

NSHTTPURLResponse *resp = (NSHTTPURLResponse *)response;

_length = [[resp.allHeaderFields objectForKey:@"Content-Length"] floatValue];

//设置状态栏接收数据状态

[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

}

//响应体

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

{

[_imageData appendData:data];//拼接响应数据

}

5.请求完成之后将图片显示出来,并且设置状态栏

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{

UIImage* image = [UIImage imageWithData:_imageData];

self.view.backgroundColor = [UIColor colorWithPatternImage:image];

//设置状态栏

[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

}

你可能感兴趣的:(iOS异步请求下载图片)