一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Swift HTTP网络操作库Alamofire实现文件下载,断点续传例子

时间:2022-06-25 23:42:33 编辑:袖梨 来源:一聚教程网

七,使用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()
    }

热门栏目