热门搜索 :
考研考公
您的当前位置:首页正文

iOS异步请求下载图片

来源:东饰资讯网

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

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

//请求

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

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

}

//响应体

- (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];

//设置状态栏

}

Top