简体   繁体   English

使用Alamofire的下载速率

[英]download rate using Alamofire

I am writing a downloader app with alamofire module using this function I want to show current download rate in MB/s and I really don't know how to achieve this please help me. 我正在使用此功能编写带有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

}

I don't think Alamofire or any other library provides download speed. 我认为Alamofire或其他任何图书馆都不提供下载速度。 Developers have to calculate themselves. 开发人员必须自己计算。 You can do it as: 您可以按照以下方式进行操作:

  • Take a global variable that saves previous downloaded bytes. 取一个保存先前下载字节的全局变量。
  • Use NSTimer with 1 sec interval to calculate the speed. 使用NSTimer以1秒的间隔来计算速度。

Code Example: 代码示例:

  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