你好,歡迎來到IOS教程網

 Ios教程網 >> IOS使用技巧 >> IOS7技巧 >> Swift HTTP網絡操作庫Alamofire實現文件下載,斷點續傳例子

Swift HTTP網絡操作庫Alamofire實現文件下載,斷點續傳例子

編輯:IOS7技巧
前面給各位有介紹過關於Swift HTTP網絡操作庫Alamofire實現文件上傳例子了,今天我們一起來看一篇關於文件下載,斷點續傳例子,希望文章能夠幫助到各位.

七,使用Alamofire進行文件下載

1,自定義下載文件的保存目錄
下面代碼將logo圖片下載下來保存到用戶文檔目錄下(Documnets目錄),文件名不變。

Alamofire.download(.GET, "http://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!)
}

2,使用默認提供的下載路徑
Alamofire內置的許多常用的下載路徑方便我們使用,簡化代碼。比如,下載到用戶文檔目錄下可以改成:

let destination = Alamofire.Request.suggestedDownloadDestination(
    directory: .DocumentDirectory, domain: .UserDomainMask)
        
Alamofire.download(.GET, "http://www.hangge.com/blog/images/logo.png",
    destination: destination)

3,下載進度

下面代碼在文件下載過程中會不斷地打印下載進度,同時下載完成後也會打印完成信息。


let destination = Alamofire.Request.suggestedDownloadDestination(
    directory: .DocumentDirectory, domain: .UserDomainMask)
        
Alamofire.download(.GET, "http://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)
}

4,斷點續傳(Resume Data)
當下載過程中被意外停止時,可以在響應方法中把已下載的部分保存起來,下次再從斷點繼續下載。
下面通過樣例演示如何斷點續傳:
(1)程序啟動後自動開始下載文件
(2)點擊“停止下載”,終止下載並把已下載的數據保存起來,進度條停止走動。
(3)點擊“繼續下載”,從上次終止的地方繼續下載,進度條繼續走動。
原文:Swift - HTTP網絡操作庫Alamofire使用詳解3(文件下載,斷點續傳)   原文:Swift - HTTP網絡操作庫Alamofire使用詳解3(文件下載,斷點續傳)


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,
            "http://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()
    }

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