1. 程式人生 > >大文件的下載

大文件的下載

cache arch progress 思路 see all end append tor

(1)實現思路

邊接收數據邊寫文件以解決內存越來越大的問題

(2)核心代碼


//當接收到服務器響應的時候調用,該方法只會調用一次
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    //0.獲得當前要下載文件的總大小(通過響應頭得到)
    NSHTTPURLResponse *res = (NSHTTPURLResponse *)response;
    self.totalLength = res.expectedContentLength;
    NSLog(@"%zd",self.totalLength);

    //創建一個新的文件,用來當接收到服務器返回數據的時候往該文件中寫入數據
    //1.獲取文件管理者
    NSFileManager *manager = [NSFileManager defaultManager];

    //2.拼接文件的全路徑
    //caches文件夾路徑
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

    NSString *fullPath = [caches stringByAppendingPathComponent:res.suggestedFilename];
    self.fullPath  = fullPath;
    //3.創建一個空的文件
    [manager createFileAtPath:fullPath contents:nil attributes:nil];

}
//當接收到服務器返回的數據時會調用
//該方法可能會被調用多次
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{

    //1.創建一個用來向文件中寫數據的文件句柄
    //註意當下載完成之後,該文件句柄需要關閉,調用closeFile方法
    NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:self.fullPath];

    //2.設置寫數據的位置(追加)
    [handle seekToEndOfFile];

    //3.寫數據
    [handle writeData:data];

    //4.計算當前文件的下載進度
    self.currentLength += data.length;

    NSLog(@"%f",1.0* self.currentLength/self.totalLength);
    self.progressView.progress = 1.0* self.currentLength/self.totalLength;
}

大文件的下載