使用Alamofire的下载速率

时间:2018-08-15 12:13:13

标签: ios swift alamofire afnetworking urlsession

我正在使用此功能编写带有alamofire模块的下载器应用程序,我想以MB / s为单位显示当前下载速率,我真的不知道该如何实现,请帮帮我。


  @IBAction func tapStartButton(_ sender: Any) {



    let fileUrl = self.getSaveFileUrl(fileName: Data[0] as String)
    let destination: DownloadRequest.DownloadFileDestination = { _, _ in
        return (fileUrl, [.removePreviousFile, .createIntermediateDirectories])
    }

    self.request = Alamofire.download(Data[0] as String , to:destination)

        .downloadProgress { (progress) in



        self.progressCircle.progress = progress.fractionCompleted




        cell.progressLabel.isHidden = false


        }

        .responseData { (data) in

            self.Data.removeFirst()
                self.startButton.isHidden = false
                self.pauseButton.isHidden = true

}

1 个答案:

答案 0 :(得分:1)

我认为Alamofire或其他任何图书馆都不提供下载速度。开发人员必须自己计算。 您可以按照以下方式进行操作:

  • 采用一个全局变量来保存以前下载的字节。
  • 使用NSTimer间隔1秒来计算速度。

代码示例:

  var prevDownloadedBytes: Int = 0
  var totalDownloadedBytes: Int = 0

  func calculateDownloadSpeed(){
   Timer.scheduleWith(timeInterval: 1.0, repeats: true){
     speed = totalDownloadedBytes - prevDownloadedBytes
     print("Speed is: \(speed) bps")
     prevDownloadedBytes = totalDownloadedBytes 
  }
}

  @IBAction func tapStartButton(_ sender: Any) {
    self.request = Alamofire.download(Data[0] as String , to:destination)
        .downloadProgress { (progress) in

        //Set Total Downloaded bytes here
        self.totalDownloadedBytes = progress.fileCompletedCount

        self.progressCircle.progress = progress.fractionCompleted
        cell.progressLabel.isHidden = false
        }
        .responseData { (data) in
            self.Data.removeFirst()
                self.startButton.isHidden = false
                self.pauseButton.isHidden = true
}