#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
iOS 异步下载图片
最新推荐文章于 2024-11-19 22:58:57 发布