iOS 异步下载图片

本文介绍了一种在iOS应用中实现图片异步加载的方法。通过NSURLConnection进行网络请求,并使用缓存策略提高加载效率。当图片加载完成后,将其显示在UIImageView上。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#import "ViewController.h"
 #define IMAGE_URL @"http://williamzhang-public.qiniudn.com/DSC_0069.jpg"
 
 @interface ViewController ()<NSURLConnectionDataDelegate>
 {
 NSMutableData *_data;
 IBOutlet UIImageView *imageView;
 }
 
 @end
 
 @implementation ViewController
 
 - (void)viewDidLoad {
 [super viewDidLoad];
 NSURL *url=[NSURL URLWithString:IMAGE_URL];
 //No.1
 //开始写代码,设置一个请求并使用异步请求的方式获取网络上的图片的数据,设置缓存策略:首先使用缓存,如果没有本地缓存,才从原地址下载 ,网络请求超时时间为5s。
 NSURLRequest *request=[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:5];
 
 
 
 
 
 NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
 
 
 
 
 //end_code
 if (connection) {
 _data=[NSMutableData data];
 }else
 {
 UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"连接失败" message:@"无法建立连接" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
 [alert show];
 }
 
 }
 -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
 {
 [_data setLength:0];
 }
 
 -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
 {
 [_data appendData:data];
 NSLog(@"收到数据的时候%@",_data);
 }
 -(void)connectionDidFinishLoading:(NSURLConnection *)connection
 {
 
 imageView.image=[UIImage imageWithData:_data];
 }
 -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
 {
 NSLog(@"%@",error);
 }
 - (void)didReceiveMemoryWarning {
 [super didReceiveMemoryWarning];
 }
 
 @end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值