標籤: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實現大檔案下載