NSURLConnection實現大檔案下載

來源:互聯網
上載者:User

標籤:nsurlconnection實現大檔案

NSURLConnection實現大檔案下載


1.方案:利用NSURLConnection和它的代理方法

1>發送一個請求
// 1.URL
NSURL *url = [NSURL URLWithString:
@"http://localhost:8080/MJServer/resources/videos.zip"];
// 2.請求
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 3.下載(建立完conn對象後,會自動發起一個非同步請求)
[NSURLConnection connectionWithRequest:request delegate:
self];

2>在代理方法中處理伺服器返回的資料
/**
 
在接收到伺服器的響應時:
 1.
建立一個空的檔案
 2.
用一個控制代碼對象關聯這個空的檔案,目的是:方便後面用控制代碼對象往檔案後面寫資料
 */

- (
void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
   
// 檔案路徑
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask,
YES) lastObject];
    NSString *filepath = [caches stringByAppendingPathComponent:
@"videos.zip"];
   
   
// 建立一個空的檔案 到 沙箱中
    NSFileManager *mgr = [NSFileManager defaultManager];
    [mgr createFileAtPath:filepath contents:
nilattributes:nil];
   
   
// 建立一個用來寫資料的檔案控制代碼
   
self.writeHandle = [NSFileHandle fileHandleForWritingAtPath:filepath];
    //獲得檔案的總大小
   
self.totalLength= response.expectedContentLength;
}

/**
 
在接收到伺服器返回的檔案資料時,利用控制代碼對象往檔案的最後面追加資料
 */

- (
void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
   
// 移動到檔案的最後面
    [
self.writeHandle seekToEndOfFile];
   
   
// 將資料寫入沙箱
    [
self.writeHandle writeData:data];
    //累計檔案的長度
   
self.currentLength+= data.length;
   
   
NSLog(@"下載進度:%f", (double)self.currentLength/self.totalLength);
   
self.circleView.progress= (double)self.currentLength/self.totalLength;
}

/**
 
在所有資料接收完畢時,關閉控制代碼對象
 */

- (
void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    self.currentLength= 0;
   
self.totalLength= 0;
   
// 關閉檔案
    [
self.writeHandle closeFile];
   
self.writeHandle =nil;
}

注意:千萬不能用NSMutableData來拼接伺服器返回的資料

NSURLConnection實現大檔案下載

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.