斷點續傳指的是從上次中斷的位置繼續下載,而不是從頭再來(本文只討論下載)。下載大檔案時,若沒有這個能力,任何一次網路抖動或用戶主動暫停,都意味著前面幾分鐘白等。
本文要特別解決一個更棘手的變體:App 被用戶 kill 掉或者 crash 之後,重啟還能接著下。要做到這點,關鍵是把「已下載的部分」可靠地持久化下來。
斷點續傳需要服務端配合,常見方式有 FTP 與 HTTP 兩種,下面聚焦 HTTP。
核心依賴 HTTP 頭部的 Range 欄位。有了它,客戶端可以只請求資源的某一段,也可以在傳輸失敗後從斷點恢復。Range 以位元組計算,且不必給出結尾位元組數,因為請求方未必知道資源總大小。當然,並非所有服務端都支援,但大多數都支援。
Range 的定義如圖 1:
圖 1. HTTP-Range

圖 2 是一個請求的頭部:
圖 2. HTTP request 例子

其中 “Range: bytes=1208765-” 表示:請給我從第 1208765 位元組開始往後的內容。
圖 3 是對應的響應:
圖 3. HTTP response 例子

這裡有三個資訊要看懂:“Accept-Ranges: bytes” 表明服務端接受按位元組的範圍請求;Content-Range: bytes 1208765-20489997/20489998 同時給出了本次返回的起止位置與整個資源的總長度;而狀態碼是 206(Partial Content),不是 200。判斷是否命中斷點續傳,就靠這個 206。
筆者專案的資源都放在 HTTP 服務器上,因此方案基於 HTTP。清單 1 是核心代碼:
清單 1. 使用 AFHTTPRequestOperation 實現斷點續傳的代碼
// 1 指定下載文件地址 URLString // 2 獲取保存的文件路徑 filePath // 3 創建 NSURLRequest NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:URLString]]; unsigned long long downloadedBytes = 0; if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) { // 3.1 若之前下載過 , 則在 HTTP 請求頭部加入 Range // 獲取已下載文件的 size downloadedBytes = [self fileSizeForPath:filePath]; // 驗證是否下載過文件 if (downloadedBytes > 0) { // 若下載過 , 斷點續傳的時候修改 HTTP 頭部部分的 Range NSMutableURLRequest *mutableURLRequest = [request mutableCopy]; NSString *requestRange = [NSString stringWithFormat:@"bytes=%llu-", downloadedBytes]; [mutableURLRequest setValue:requestRange forHTTPHeaderField:@"Range"]; request = mutableURLRequest; } } // 4 創建 AFHTTPRequestOperation AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; // 5 設置操作輸出流 , 保存在第 2 步的文件中 operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:YES]; // 6 設置下載進度處理 block [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) { // bytesRead 當前讀取的字節數 // totalBytesRead 讀取的總字節數 , 包含斷點續傳之前的 // totalBytesExpectedToRead 文件總大小 }]; // 7 設置 success 和 failure 處理 block [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { } failure:^(AFHTTPRequestOperation *operation, NSError *error) { }]; // 8 啟動 operation [operation start];
兩個要害:一是把已下載位元組數寫進 Range 頭;二是 outputStream 用 append:YES,否則新資料會把舊的覆蓋掉。
再往裡看一層:AFHTTPRequestOperation 繼承自 AFURLConnectionOperation,後者實現了 NSURLConnectionDataDelegate。
處理流程如圖 4:
圖 4. AFURLHTTPrequestOperation 處理流程

順帶解釋一個常被問到的設計選擇:為什麼要在子線程調異步介面?如果在主線程直接呼叫 [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES],監聽任務會被掛進主線程的 Runloop,而 RunloopMode 默認是 NSDefaultRunLoopMode——只有當前線程的 Runloop 正處理該模式時任務才會執行。用戶一滾動 TableView/ScrollView,主線程切到 NSEventTrackingRunLoop 模式,下載就集體卡住。放到子線程即可規避。
反過來,也因為在子線程,DownloadProgressBlock、success 與 failure 都需要切回主線程更新 UI。
關鍵是實現 NSURLConnectionDataDelegate 的三個方法:
清單 2. NSURLConnection 的實現
// SWIFT // 請求失敗處理 func connection(connection: NSURLConnection, didFailWithError error: NSError) { self.failureHandler(error: error) } // 接收到服務器響應是調用 func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse) { if self.totalLength != 0 { return } self.writeHandle = NSFileHandle(forWritingAtPath: FileManager.instance.cacheFilePath(self.fileName!)) self.totalLength = response.expectedContentLength + self.currentLength } // 當服務器返回實體數據是調用 func connection(connection: NSURLConnection, didReceiveData data: NSData) { let length = data.length // move to the end of file self.writeHandle.seekToEndOfFile() // write data to sanbox self.writeHandle.writeData(data) // calculate data length self.currentLength = self.currentLength + length print("currentLength\(self.currentLength)-totalLength\(self.totalLength)") if (self.downloadProgressHandler != nil) { self.downloadProgressHandler(bytes: length, totalBytes: self.currentLength, totalBytesExpected: self.totalLength) } } // 下載完畢後調用 func connectionDidFinishLoading(connection: NSURLConnection) { self.currentLength = 0 self.totalLength = 0 //close write handle self.writeHandle.closeFile() self.writeHandle = nil let cacheFilePath = FileManager.instance.cacheFilePath(self.fileName!) let documenFilePath = FileManager.instance.documentFilePath(self.fileName!) do { try FileManager.instance.moveItemAtPath(cacheFilePath, toPath: documenFilePath) } catch let e as NSError { print("Error occurred when to move file: \(e)") } self.successHandler(responseObject:fileName!) }
如圖 5 所示,這是 NSURLConnection 的一般處理流程。
圖 5. NSURLConnection 流程

對照流程落地:在 didReceiveResponse 中初始化 fileHandle 並把已下載長度加進總長;在 didReceiveData 中 seekToEndOfFile 後追加寫入中間檔;在 connectionDidFinishLoading 中清空計數、關閉 handle,並把暫存檔移到 Document 目錄。這樣一來,無論是請求異常還是 App 被殺,重啟後都能靠中間檔續傳。
初始化時記得把 scheduleInRunLoop 設為 NSRunLoopCommonModes,否則進度條 UI 不會更新——這正是前面 Runloop 問題的具體解法。
實現效果如圖 6:
圖 6. NSURLConnection 演示

蘋果從 iOS 7 起推出了 NSURLSession,具備 NSURLConnection 的全部能力且更強大。由於 NSURLConnection 從 2015 年開始已被棄用,新專案建議直接基於 NSURLSession 實作。兩者 delegate 方法的映射關係如圖 7,重點是滿足 NSURLSessionDataDelegate 與 NSURLSessionTaskDelegate。
圖 7. 協議之間映射關系

代碼整體與方案一相似:
清單 3. NSURLSessionDataTask 的實現
// SWIFT // 接收數據 func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, idReceiveData data: NSData) { //. . . } // 接收服務器響應 func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) { // . . . completionHandler(.Allow) } // 請求完成 func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { if error == nil { // . . . self.successHandler(responseObject:self.fileName!) } else { self.failureHandler(error:error!) } }
最大差異在 didCompleteWithError:它把 NSURLConnection 裡的 connection:didFailWithError: 與 connectionDidFinishLoading: 合併成了一個,所以要靠 error 是否為 nil 來分流成功與失敗分支。
實現效果如圖 8:
圖 8. NSURLSessionDataTask 演示

這是 NSURLSession 專門用於下載的子類,對應協議為 NSURLSessionDownloadDelegate,如圖 9:
圖 9. NSURLSessionDownloadDelegate 協議

有一個坑要牢記:didFinishDownloadingToURL 返回之後,系統會自動刪除 temp 目錄下的檔案,所以所有檔案搬移操作都必須在這個方法內部完成。筆者曾想直接找到那個 tmp 檔做續傳,無奈始終摸不到路徑,只能寄望 Swift 開源後能有答案。
基於 DownloadTask 的續傳,需要在 cancelByProducingResumeData 中保存已下載的資料;進度通知則在 URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesWritten:totalBytesExpectedToWrite: 裡處理,非常省事。
代碼如清單 4:
清單 4. NSURLSessionDownloadTask 的實現
//SWIFT //UI 觸發 pause func pause(){ self.downloadTask?.cancelByProducingResumeData({data -> Void in if data != nil { data!.writeToFile(FileManager.instance.cacheFilePath(self.fileName!), atomically: false) } }) self.downloadTask = nil } // MARK: - NSURLSessionDownloadDelegate func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { if (self.downloadProgressHandler != nil) { self.downloadProgressHandler(bytes: Int(bytesWritten), totalBytes: totalBytesWritten, totalBytesExpected: totalBytesExpectedToWrite) } } func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { if error != nil {//real error self.failureHandler(error:error!) } } func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) { let cacheFilePath = FileManager.instance.cacheFilePath(self.fileName!) let documenFilePath = FileManager.instance.documentFilePath(self.fileName!) do { if FileManager.instance.fileExistsAtPath(cacheFilePath){ try FileManager.instance.removeItemAtPath(cacheFilePath) } try FileManager.instance.moveItemAtPath(location.path!, toPath: documenFilePath) } catch let e as NSError { print("Error occurred when to move file: \(e)") } self.successHandler(responseObject:documenFilePath) }
實現效果如圖 10:
圖 10. NSURLSessionDownloadTask 演示

三種方案的取捨很清晰:維護老專案用 NSURLConnection;新專案想要控制粒度用 NSURLSessionDataTask;只是單純下載大檔、希望系統幫你管斷點,用 NSURLSessionDownloadTask 最省心。下載這塊的水遠比這篇深,這裡只把最關鍵的路徑鋪出來,後續在實際項目中還有很多值得細修的細節。