首页 > 解决方案 > 使用 Alamofire 的下载速率

问题描述

我正在使用此功能编写一个带有 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

}

标签: iosswiftalamofireafnetworkingurlsession

解决方案


我不认为 Alamofire 或任何其他库提供下载速度。开发人员必须自己计算。你可以这样做:

  • 取一个保存先前下载字节的全局变量。
  • 使用NSTimer1 秒间隔计算速度。

代码示例:

  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
}

推荐阅读