繁体   English   中英

使用Alamofire的下载速率

[英]download rate using 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

}

我认为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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM