4

I am trying to download a file using Alamofire. To show progress, i am using downloadProgress from alamofire. I got the progress percentage from it. But i need to show the total Mb/Kb downloaded so far and estimated time remaining as well. Here is my code:

AF.download("http://ipv4.download.thinkbroadband.com/200MB.zip",
                method: .get,
                parameters: nil,
                encoding: URLEncoding.default,
                headers: nil,
                interceptor:nil,
                to: destination)
                .downloadProgress { progress in
                    self.postProgress(progress: progress)
                }
                .responseData { response in
                    if let data = response.result.value {
//                        let image = UIImage(data: data)
                    }
            }

Posting the progress using notification

func postProgress(progress: Progress) {
        NotificationCenter.default.post(name: .DownloadProgress, object: progress)
    }

Showing my progress using the following codes

if let progress = notification.object as? Progress {
            progressBar.setProgress(Float(progress.fractionCompleted), animated: true)
            progressInNumberView.text = "\(Int64(progress.fractionCompleted*100))%"
            remianingView.text = "\(progress.fileCompletedCount) / \(progress.fileTotalCount)"
            if let estimatedTimeRemaining = progress.estimatedTimeRemaining {

                remianingView.text = format(estimatedTimeRemaining)
            }
        }

I am getting progress.fractionCompleted perfectly. But progress.estimatedTimeRemaining, progress.fileCompletedCount and progress.fileTotalCount is always nil.

Ahsan Aasim
  • 1,177
  • 3
  • 14
  • 40

2 Answers2

0

Simple DownloadProgress class implementation based on having a Progress from Alamofire or other and a moving average taken from here How to estimate download time remaining (accurately)?

https://gist.github.com/akovalov/7b22735e1fb7f1117bf04659e214d785

smartwolf
  • 300
  • 2
  • 12
-1

I you check the Progress class you can find

open var totalUnitCount: Int64
open var completedUnitCount: Int64

you can use those variables

Inder Kumar Rathore
  • 39,458
  • 17
  • 135
  • 184
  • I got the byte counts from totalUnitCount & completedUnitCount. Can you tell me how i can get or calculate the estimatedTimeRemaining? – Ahsan Aasim Mar 18 '19 at 05:19
  • That's tricky if the `progress.estimatedTimeRemaining` is nil, then you might write your own logic. You've total and received bytes, just count the time difference between each progress and make your own calculations. But before doing your own implementation just ask alamofire why `estimatedTimeRemaining` is nil – Inder Kumar Rathore Mar 18 '19 at 09:20