標籤:非同步 delegate 資料 下載 ios開發
下載資料可以使用同步請求,非同步請求
之前有講到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]; }
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
資料下載 - delegate 形式的非同步請求