標籤:http 非同步下載 ios
//建立imageVIew對象
- (void)createImageView
{
UIImageView *imageView = [[UIImageView alloc]init]; //1
imageView.frame = CGRectMake(30, 120, 300, 400);
imageView.backgroundColor = [UIColor redColor];
[self.view addSubview:imageView];//2
//[imageView release] //1(ARC記憶體管理系統自動釋放)
_imageView = imageView;
}
//建立下載按鈕
- (void)createBtn
{
UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
btn.frame = CGRectMake(50, 50, 200, 50);
[btn setTitle:@"下載資料" forState:UIControlStateNormal];
btn.titleLabel.font = [UIFont systemFontOfSize:26];
btn.backgroundColor = [UIColor orangeColor];
[btn addTarget:self action:@selector(downLoadData) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}
//實現下載資料方法
- (void)downLoadData
{
//1.建立url對象
NSURL *url = [NSUR URLWithString:@"http://a.hiphotos.baidu.com/image/w%3D310/sign=72d5d600362ac65c67056072cbf3b21d/8435e5dde71190ef3e9498bfcd1b9d16fdfa6066.jpg"];
//2.建立請求對象
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
//3.建立非同步下載連線物件
//參數1:請求對象
//參數2:代理對象,由於是非同步下載,則調用了這行代碼後會立即執行後續的代碼,只有通過代理對象實現協議的方法來接收伺服器傳過來的資訊
//參數3:開始標誌,是否立即啟動yes:立即啟動 no:手動啟動(需調用start方法)
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:NO];
//同步下載資料,會讓UI主線程阻塞,因為主線程會一直等待資料下載完成或者下載出錯返回才能繼續往下執行進入事件迴圈當中(runLoop)
//非同步下載資料,UI主線程會開啟一個新的線程,然後讓線程去做下載的事情,然後立馬往下執行進入事件迴圈,並且通過代理協議傳遞給代理對象處理相應的資料或調用方法處理資料
//4.手動開始啟動串連(通過三向交握建立串連)
[conn start];
}
#pragma mark-連線協定方法 NSURLConnectionDelegate
//1.傳輸失敗調用方法
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"傳輸失敗,error=%@",error);
}
#pragma mark-串連資料協議方法 NSURLConnectionDataDelegate
//1.收到應答包調用方法
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"收到應答包,responese=%@",response);
}
//2.收到資料包調用方法,這個方法會被調用多次
//當資料比較大的時候,伺服器會將資料分塊傳輸
//當本地有緩衝時,這個方法只調用一次,即在擷取到本機快取的資料時調用
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"收到資料");
//2.1儲存每次取到的資料,因為資料可能會分多次傳輸
[_data appendData:data];
}
//3.結束傳輸資料調用方法
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"下載完成");
//3.1將資料轉成圖片對象
UIImage *image = [UIImage imageWithData:_data];
//3.2將圖片對象傳給imageView
_imageView.image = image;
//3.3清空儲存的資料
[_data setLength:0];
}
HTTP_非同步下載