简体   繁体   中英

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.


  @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. 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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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