在iOS中可以这样获取一张网络图片
代码语言:javascript复制 NSURL *url = [NSURL URLWithString:@"https://img.yuanmabao.com/zijie/pic/2021/10/29/pqy5ykcrhsu.jpg"];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
UIImage *img = [UIImage imageWithData:data];
但是图片比较大的时候程序会卡在这里,所以我们要用异步请求来下载图片
1.新建一个single view工程
2.ViewController.h文件:
代码语言:javascript复制 @interface ViewController : UIViewController <NSURLConnectionDataDelegate> {
NSMutableData* _imageData;//如果图片比较大的话,response会分几次返回相应数据,所以需要用NSMutableData来接受数据
float _length;
}
@end
3.ViewController.m文件:
代码语言:javascript复制 - (void)viewDidLoad
{
[super viewDidLoad];
//初始化图片数据
_imageData = [[NSMutableData alloc] init];
//请求
NSURL *url = [NSURL URLWithString:@"https://img.yuanmabao.com/zijie/pic/2021/10/29/pqy5ykcrhsu.jpg"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//连接
[NSURLConnection connectionWithRequest:request delegate:self];
} </pre>
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];//拼接响应数据
} </pre>
5.请求完成之后将图片显示出来,并且设置状态栏
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
UIImage* image = [UIImage imageWithData:_imageData];
self.view.backgroundColor = [UIColor colorWithPatternImage:image];
//设置状态栏
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}