【Swift】基于Alamofire 下载文件

  1. Swift 4.2 Alamofire 4.8.2
  • 今天升级老项目的下载文件等功能(很头疼)
  • 首先我们抽出三个全局变量
    /// 下载请求对象
    var downloadRequest: DownloadRequest!
    /// //下载文件的保存路径
    var destination : DownloadRequest.DownloadFileDestination!
    //用于停止下载时,保存已下载的部分
    var cancelledData: Data?
    /// 后台下载地址
    var FilePath = “”
  • 在开始下载的点击事件中进行下载的开发
  /**
     下载
     */
   @objc func actionDownload(){
    print(FilePath)
    /// 下载目的
    self.destination = { _, response in
        // 下载到Documents中的哪个文件夹folioName这里是文件夹
        let documentURL = URL(fileURLWithPath: NSHomeDirectory() + "/Documents/\(self.folioName)/")
        // 在路径追加文件名称
        let fileUrl = documentURL.appendingPathComponent(response.suggestedFilename!)
        // .createIntermediateDirectories:如果指定了目标URL,将会创建中间目录。
        // .removePreviousFile:如果指定了目标URL,将会移除之前的文件
        return (fileUrl , [.removePreviousFile, .createIntermediateDirectories])
    }
    
    downloadRequest = Alamofire.download(URL(string: XXXXXXXXXXXXXX!)!, method: HTTPMethod.get, to: destination)
    self.downloadRequest.downloadProgress(closure: downloadProgress1)
    self.downloadRequest.responseData(completionHandler: downloadResponse)
    }
  • 对下载进度的监听
    func downloadProgress1(progress: Progress){
        
        print("\(Float(progress.fractionCompleted))------\(Float(progress.totalUnitCount))")
        // 进度条更新
    }
//下载停止响应(不管成功或者失败)
    func downloadResponse(response: DownloadResponse){
        switch response.result {
        case .success:
            //self.image = UIImage(data: data)
            print("文件下载完毕: \(response)")
            downLoadSuccess()
        case .failure:
            self.cancelledData = response.resumeData //意外终止的话,把已下载的数据储存起来
    }

    }
  • 断点续传
/**
     点击暂停还是点击继续
     
     - parameter isStop: ture 暂停 ,false 继续
     */
    func actionStopOrGoWith(isStop: Bool) {
        if(isStop){
            self.downloadRequest?.cancel()
        }else{
            if let cancelledData = self.cancelledData {
                self.downloadRequest = Alamofire.download(resumingWith: cancelledData, to: destination)
                self.downloadRequest.downloadProgress(closure: downloadProgress1)
                self.downloadRequest.responseData(completionHandler: downloadResponse)
            }else{
            }
        }
    }

Swift 2.3

    /// 下载请求对象
    var downloadRequest: Request

 let urlString = FilePath.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
        downloadRequest = Alamofire.download(.GET, urlString, 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)
            print("\(Float(totalBytesRead))----\(Float(totalBytesExpectedToRead))")
            // 进度条更新
            dispatch_async(dispatch_get_main_queue(), {
//                self.progress.setProgress(percent,animated:true)
                self.downView.changeDownLoadProgrees(Float(totalBytesRead), totalBytesExpectedToRead: Float(totalBytesExpectedToRead))
            })
//            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 {
                
//                let filePath:String = NSHomeDirectory() + "/Documents/QQ7.9.exe"
                
//                print("Successfully downloaded file: \(response)")
                
                downLoadSuccess()
                
            }
    }

 /**
     点击暂停还是点击继续
     
     - parameter isStop: ture 暂停 ,false 继续
     */
    func actionStopOrGoWith(isStop: Bool) {
        if(isStop){
           self.downloadRequest?.cancel()
        }else{
            if let cancelledData = self.cancelledData {
                self.downloadRequest = Alamofire.download(resumeData: cancelledData,
                    destination: destination)
                self.downloadRequest.progress(downloadProgress) //下载进度
                self.downloadRequest.response(completionHandler: downloadResponse) //下载停止响应
            }else{
            }
        }
    }

你可能感兴趣的:(Swift)