檔案下載看似簡單,真正難的是中斷之後還能接著下。本文先講完備的基本步驟,再直接以斷點續傳為例說明差異在哪。
1. 取得下載連結,建立請求並送出。請務必使用異步請求,否則大檔下載會把主線程卡住。
2. 收到回應後,在下載目錄中建立檔案。這裡用 NSFileHandle 做檔案內部處理,流程是:先用 NSFileManager 確認檔案是否存在,不存在則建立,再用 NSFileHandle 的 fileHandleForWritingAtPath: 取得寫入句柄。
3. 資料分段送達時,把每一段寫入檔案。
4. 接收完畢後關閉 NSFileHandle。
這部分很直觀,就不佔篇幅了。以下直接看斷點續傳。
沙盒路徑在本例中會反覆用到,先抽成一個方法:
-(NSString *)getFilePath {
NSString *document = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *filePath = [document stringByAppendingPathComponent:_fileName];
return filePath;
}
- (IBAction)download:(UIButton *)sender {
NSString *string = @"https://221.228.249.8/2/b/k/h/o/bkhoxvtmbviswrdeddgvxcbufzwvwb/he.yinyuetai.com/631B014A6B0FCDF25944EB816345F6A6.flv";
// 以 "/" 切開取得檔名
NSArray *array = [string componentsSeparatedByString:@"/"];
_fileName = [array lastObject];
// 網址含中文時必須轉碼,否則無法識別
string = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:string];
// 用可變請求,因為續傳時要改寫標頭
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 判斷先前是否已下載過一部分
if ([[NSFileManager defaultManager] fileExistsAtPath:[self getFilePath]]) {
// 取得檔案資訊,其中 NSFileSize 即已下載的位元組數
NSDictionary *fileDic = [[NSFileManager defaultManager] attributesOfItemAtPath:[self getFilePath] error:nil];
NSLog(@"%@", fileDic);
_receiviceSize = [fileDic[NSFileSize] longLongValue];
// Range 標頭的幾種常見形式:
// bytes=0-499 要求前 500 個位元組
// bytes=500- 要求第 500 位元組之後的全部內容
// bytes=500-1000 要求 500 到 1000 之間的片段
// bytes=0-1,499-500 一次要求多個片段
NSString *bytes = [NSString stringWithFormat:@"bytes=%lld-", _receiviceSize];
[request setValue:bytes forHTTPHeaderField:@"Range"];
}
_connection = [NSURLConnection connectionWithRequest:request delegate:self];
}
- (IBAction)pause:(UIButton *)sender {
[_connection cancel];
_connection = nil;
}
// 收到回應
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// 為了取得狀態碼,需轉型為 NSHTTPURLResponse
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSDictionary *responseHead = httpResponse.allHeaderFields;
// 已下載 + 剩餘 = 檔案總大小
_totalSize = _receiviceSize + [responseHead[@"Content-Length"] longLongValue];
NSFileManager *manager = [NSFileManager defaultManager];
if ([manager fileExistsAtPath:[self getFilePath]] == NO) {
[manager createFileAtPath:[self getFilePath] contents:nil attributes:nil];
}
_fileHandle = [NSFileHandle fileHandleForWritingAtPath:[self getFilePath]];
}
// 收到資料
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// 把游標移到檔案末尾再寫入(預設是從頭部寫)
[_fileHandle seekToEndOfFile];
[_fileHandle writeData:data];
// 即時更新已接收長度
_receiviceSize = _receiviceSize + data.length;
}
// 接收完畢
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[_fileHandle closeFile];
}
seekToEndOfFile 是續傳能成立的技術核心。NSFileHandle 的游標預設在檔案開頭,若不主動移到底部,新收到的資料會把舊內容覆蓋掉,最終檔案反而變小。
其次,Range 標頭能否生效完全取決於伺服器。判斷方式是檢查回應狀態碼:206 Partial Content 代表伺服器接受續傳;若回傳 200,表示它忽略了 Range 而送出整個檔案,此時必須把 _receiviceSize 歸零並清空既有檔案,否則檔案會因為重複拼接而損壞。
最後别忘了在接收到失敗回呼(connection:didFailWithError:)時關閉 fileHandle 並保留暫存檔,這樣下次點擊下載才能從中斷處接續。