下载数据可以使用同步请求,异步请求
之前有讲到NSString 、 NSData 类型的同步请求
有NSURLConnection 形式的同步请求
异步请求有block 形式的异步请求,我们需要创建一个队列 在block 内部实现
但是我们最常用的是 delegate 形式的异步请求
#import "ViewController.h"
@interface ViewController ()<NSURLConnectionDataDelegate>
@property(nonatomic,weak)IBOutlet UIButton *button;
@property(nonatomic,weak)IBOutlet UIImageView *imageView;
@property(nonatomic,weak)IBOutlet UIProgressView *progressView;
@property(nonatomic,retain)NSString *myURLStr;
@property(nonatomic,retain)NSMutableData *result;
@property(nonatomic,assign)float totalSize;
@end
@implementation ViewController
//懒加载
-(NSMutableData *)result
{
if(_result == nil)
{
//_result = [[NSMutableData alloc]init];
_result = [NSMutableData data];
}
return _result;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
-(IBAction)downloadBegin:(id)sender{
self.myURLStr = @"http://farm3.staticflickr.com/2846/9823925914_78cd653ac9_b_d.jpg";
//self.myURLStr = @"http://photo.candou.com/i/114/826ea823e8ffe792a6fda9e126f6c404";
//[self syncDownloadWithConnection];
//[self asyncDownloadWithBlock];
[self asyncDownloadWithDelegate];
}
//连接有相应,开始下载
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
self.progressView.hidden = NO;
//获取数据的总长度
self.totalSize = response.expectedContentLength;
NSLog(@"%@",NSStringFromSelector(_cmd));
}
//调用表示正在接受数据 根据大小反复不间断接受
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.result appendData:data];
float pv = self.result.length /self.totalSize;
self.progressView.progress = pv;
NSLog(@"下载进度%f",pv);
NSLog(@"%@",NSStringFromSelector(_cmd));
}
//调用证明下载完毕
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
self.progressView.hidden = YES;
self.imageView.image = [UIImage imageWithData:self.result];
NSLog(@"%@",NSStringFromSelector(_cmd));
}
//连接发生错误 下载失败
//1.断网了
//2.网址出错了
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
self.progressView.hidden = YES;
NSLog(@"%@",NSStringFromSelector(_cmd));
NSLog(@"下载失败");
}
#pragma mark -NSURLConnection异步请求-
//Delegate 形式的异步请求
-(void)asyncDownloadWithDelegate{
NSURL *url = [NSURL URLWithString:self.myURLStr];
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
self.result.length = 0;
[NSURLConnection connectionWithRequest:request delegate:self];
}