七,使用Alamofire進行檔案下載
1,自訂下載檔案的儲存目錄
下面代碼將logo圖片下載下來儲存到使用者文檔目錄下(Documnets目錄),檔案名稱不變。
Alamofire.download(.GET, "yun_qi_img/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, "yun_qi_img/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()
}