您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 教學 >> iOS 相關教學

iOS 斷點續傳實踐總結:原理與三種實作方案

編輯:iOS 相關教學

前言

為什麼需要斷點續傳

斷點續傳的意思,是從上次中斷的位置接著下載或上傳,而不是從頭再來(本文只討論下載)。當檔案很大時,如果沒有這個機制,任何一次網路異常或使用者的主動暫停,都意味著要重新下載幾百 MB,既浪費時間也浪費流量。

所以只要是會下載大檔案的專案,斷點續傳幾乎是標配。而其中有一種特別棘手的情況:App 被使用者強制關閉,或者直接 crash。要讓重啟之後還能接續下載,就必须把已下載的內容確實落地成檔案,而不能只留在記憶體裡。這正是本文想解決的問題。

斷點續傳的原理

要支援斷點續傳,伺服器端必須配合。目前最常見的兩種協定是 FTP 與 HTTP,以下說明 HTTP 的做法。

HTTP

HTTP 的斷點續傳主要依賴標頭中定義的 Range。當你只想取用某個區間的資源時,Range 可以讓請求更有效率,也能在傳輸失敗後從中斷處恢復。有了它,用戶端就能針對「先前沒抓到的那一段」再發一次請求,而不必重抓整份檔案。當然,並非所有伺服器都支援 Range,但大多數都有。Range 以位元組計算,而且請求時不必給出結尾位置,因為呼叫端未必知道檔案總大小。

Range 的定義如下圖 1 所示:

圖 1. HTTP-Range

圖 2 是一個 HTTP request 的標頭範例:

圖 2. HTTP request 例子

其中的 “Range: bytes=1208765-” 代表:請把資源中第 1208765 位元組之後的內容給我。

圖 3 是對應的 HTTP response 標頭:

圖 3. HTTP response 例子

“Accept-Ranges: bytes” 表示伺服器接受指定區間的請求,允許以位元組為單位存取;Content-Range: bytes 1208765-20489997/20489998 則說明了本次回傳的內容在原始實體中的位置,以及整份資源的總長度。這裡有個關鍵細節:狀態碼是 206(Partial Content),而不是 200。如果你的程式碼用 200 來判斷成功,就會漏掉這些回應。

方案分析:AFHTTPRequestOperation

原理釐清之後就能動手實作了。由於筆者專案的資源都放在 HTTP 伺服器上,因此以下都基於 HTTP。先來看 AFNetworking 提供的做法,清單 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 若先前下載過,在請求標頭加上 Range
    // 取得已下載檔案的大小
    downloadedBytes = [self fileSizeForPath:filePath];

    // 驗證是否真的下載過內容
    if (downloadedBytes > 0) {
        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 設定輸出串流,以 append 方式續寫到第 2 步的檔案
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:YES];

// 6 設定下載進度回呼
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
    // bytesRead:本次讀取的字元組數
    // totalBytesRead:累計讀取量,含續傳之前的部分
    // totalBytesExpectedToRead:檔案總大小
}];

// 7 設定成功與失敗回呼
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    }];

// 8 啟動
[operation start];

寫完這幾步,斷點續傳就成立了:不論是 App 重啟還是中途異常,都能從已下載的部分接續。關鍵在於「把已下載的資料持久化」——也就是 outputStream 的 append 模式。

接著看看 AFHTTPRequestOperation 內部是怎麼做到的。查閱原始碼可以發現,它繼承自 AFURLConnectionOperation,而後者實作了 NSURLConnectionDataDelegate 協定。

處理流程如下圖 4 所示:

圖 4. AFURLHTTPRequestOperation 處理流程

至於為什麼 AFNetworking 要用子執行緒呼叫非同步介面,而不是直接呼叫?這是因為在主執行緒呼叫非同步介面會遇到 RunLoop 的問題。當主執行緒執行 [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES] 時,請求送出後的監聽任務會被加入主執行緒的 RunLoop,而 RunLoopMode 預設為 NSDefaultRunLoopMode,意思是只有當下的 RunLoop 正處理 NSDefaultRunLoopMode 時,這個任務才會被執行。但使用者滑動 TableView 或 ScrollView 時,主執行緒的 RunLoop 會切到 NSEventTrackingRunLoop,NSDefaultRunLoopMode 的任務就被擱置了——下載看起來就像卡住。

另外,因為是在子執行緒呼叫,所以 DownloadProgressBlock、success 與 failure Block 都需要切回主執行緒處理 UI 更新。

實戰:三種實作方式

NSURLConnection

基於 NSURLConnection 實作,關鍵是滿足 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
    // 移到檔案結尾
    self.writeHandle.seekToEndOfFile()
    // 寫入沙盒
    self.writeHandle.writeData(data)
    // 累加長度
    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
    // 關閉檔案 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 中把資料逐段寫入檔案、在 connectionDidFinishLoading 中收尾並把檔案搬到 Documents 目錄。因此不論是請求異常還是被使用者強制關閉,都能靠這個中間檔案續傳。

初始化 NSURLConnection 時要注意設定 scheduleInRunLoop 為 NSRunLoopCommonModes,否則會出現進度條 UI 不更新的現象——這正是前面提到的 RunLoop mode 問題。

實作效果如下圖 6:

圖 6. NSURLConnection 演示

NSURLSessionDataTask

蘋果從 iOS 7 開始推出 NSURLSession,它具備 NSURLConnection 的所有能力,而且更強大。由於 NSURLConnection 已從 2015 年起被標記為棄用,建議新專案直接基於 NSURLSession 實作。兩者的 delegate 方法對應關係如下圖 7,關鍵是滿足 NSURLSessionDataDelegate 與 NSURLSessionTaskDelegate。

圖 7. 協定之間的對應關係

程式碼如清單 3,大致與 NSURLConnection 的寫法相同。

清單 3. NSURLSessionDataTask 的實作

 // SWIFT

// 接收資料
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData 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 演示

NSURLSessionDownloadTask

最後來看 NSURLSession 專門負責下載的類別 NSURLSessionDownloadTask,對應的協定是 NSURLSessionDownloadDelegate,如下圖 9:

圖 9. NSURLSessionDownloadDelegate 協定

要特別注意的是,在 didFinishDownloadingToURL 之後,系統會自動刪除暫存目錄下對應的檔案,所以所有檔案操作都必須在這個方法裡面完成。筆者原本想直接找到那個暫存檔、以它為基礎做續傳,但一直找不到路徑,只能作罷。

基於 DownloadTask 實作時,需要在 cancelByProducingResumeData 中把已下載的資料存起來,下次再拿這份 resumeData 續傳。進度通知則直接在 URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite: 裡實作即可。

程式碼如清單 4:

清單 4. NSURLSessionDownloadTask 的實作

 // SWIFT

// UI 觸發暫停
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 {
        // 真正的錯誤
        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 演示

總結

以上就是 iOS 斷點續傳的原理與實踐整理。三種方案各有取向:NSURLSessionDownloadTask 最省事,系統幫你管理暫存與續傳資料;NSURLSessionDataTask 與 NSURLConnection 則讓你能完全掌握寫檔時機,適合需要自訂檔案處理邏輯的場景。實際專案中的下載機制遠不只這些細節(還牽涉併發佇列、檔案完整性驗證、斷線重試策略等),這裡只涵蓋最核心的部分,後續累積到更多經驗再與大家分享。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved