您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 7 技巧

Alamofire 詳解(三):檔案下載、進度追蹤與斷點續傳實作

編輯:iOS 7 技巧

談过上傳,接著來看下載。Alamofire 的下載 API 在預設行為之外提供了不少便利設計,尤其是「斷點續傳」——這對幾百 MB 的安裝包或影音內容來說幾乎是必需品,行動網路一不穩就得從頭再來,使用者體驗會非常糟。

一、自訂下載後的存檔位置

下面這段把圖片存進 App 的 Documents 目錄,並沿用伺服器建議的檔名:

Alamofire.download(.GET, "https://www.hangge.com/blog/images/logo.png") {
    temporaryURL, response in
    let fileManager = NSFileManager.defaultManager()
    let directoryURL = fileManager.URLsForDirectory(.DocumentDirectory,
                                                    inDomains: .UserDomainMask)[0]
    let pathComponent = response.suggestedFilename

    return directoryURL.URLByAppendingPathComponent(pathComponent!)
}

二、使用內建的下載路徑

Alamofire 已內建了幾個常用目錄的捷徑,可以省下自己組路徑的功夫:

let destination = Alamofire.Request.suggestedDownloadDestination(
    directory: .DocumentDirectory, domain: .UserDomainMask)

Alamofire.download(.GET, "https://www.hangge.com/blog/images/logo.png",
                   destination: destination)

三、追蹤下載進度

let destination = Alamofire.Request.suggestedDownloadDestination(
    directory: .DocumentDirectory, domain: .UserDomainMask)

Alamofire.download(.GET, "https://www.hangge.com/favicon.ico", destination: destination)
    .progress { (bytesRead, totalBytesRead, totalBytesExpectedToRead) in
        let percent = totalBytesRead * 100 / totalBytesExpectedToRead
        print("已下載:\(totalBytesRead)  當前進度:\(percent)%")
    }
    .response { (request, response, _, error) in
        print(response)
    }

四、斷點續傳(Resume Data)

做法是這樣:下載被中斷時,在回應方法裡把 data(也就是 resume data)保存下來;下次點擊繼續時,改用 download(resumeData:) 開一個新請求,Alamofire 會自動帶上 Range 標頭向伺服器續傳。

完整範例的功能流程:App 啟動後自動開始下載;按「停止下載」中止並保存已下載的片段,進度條停住;按「繼續下載」則從斷點接續,進度條接著往前跑。

import UIKit
import Alamofire

class ViewController: UIViewController {

    @IBOutlet weak var stopBtn: UIButton!        // 停止下載
    @IBOutlet weak var continueBtn: UIButton!    // 繼續下載
    @IBOutlet weak var progress: UIProgressView! // 進度條

    // 存檔位置
    let destination = Alamofire.Request.suggestedDownloadDestination(
        directory: .DocumentDirectory, domain: .UserDomainMask)

    // 停止時用來保存已下載的部分
    var cancelledData: NSData?

    // 下載請求物件
    var downloadRequest: Request!

    override func viewDidLoad() {
        super.viewDidLoad()

        // 頁面載入完成即自動開始下載
        self.downloadRequest = Alamofire.download(.GET,
            "https://dldir1.qq.com/qqfile/qq/QQ7.9/16621/QQ7.9.exe",
            destination: destination)

        self.downloadRequest.progress(downloadProgress)
        self.downloadRequest.response(completionHandler: downloadResponse)
    }

    // 下載過程中更新進度條
    func downloadProgress(bytesRead: Int64, totalBytesRead: Int64,
                          totalBytesExpectedToRead: Int64) {
        let percent = Float(totalBytesRead) / Float(totalBytesExpectedToRead)

        dispatch_async(dispatch_get_main_queue(), {
            self.progress.setProgress(percent, animated: true)
        })
        print("當前進度:\(percent * 100)%")
    }

    // 下載結束的回應(不論成功或失敗)
    func downloadResponse(request: NSURLRequest?, response: NSHTTPURLResponse?,
                          data: NSData?, error: NSError?) {
        if let error = error {
            if error.code == NSURLErrorCancelled {
                self.cancelledData = data   // 被取消時,保存已下載的資料
            } else {
                print("Failed to download file: \(response) \(error)")
            }
        } else {
            print("Successfully downloaded file: \(response)")
        }
    }

    // 停止
    @IBAction func stopBtnClick(sender: AnyObject) {
        self.downloadRequest?.cancel()
        self.stopBtn.enabled = false
        self.continueBtn.enabled = true
    }

    // 續傳
    @IBAction func continueBtnClick(sender: AnyObject) {
        if let cancelledData = self.cancelledData {
            self.downloadRequest = Alamofire.download(resumeData: cancelledData,
                                                      destination: destination)
            self.downloadRequest.progress(downloadProgress)
            self.downloadRequest.response(completionHandler: downloadResponse)

            self.stopBtn.enabled = true
            self.continueBtn.enabled = false
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

兩個實務眉角

第一,斷點續傳能否成功,取決於伺服器是否回應 Accept-Ranges: bytes;若伺服器不支援,resume data 會失效,這時要記得清空暫存並提示使用者重新下載。第二,resume data 只是一段暫時的 NSData,App 被砍掉重開就沒了,正式專案通常會把它寫進檔案系統,並在上線時檢查過期時間,避免拿一份太舊的續傳資料去拼檔案。

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