检索Alamofire估计时间剩余时间和文件下载大小

时间:2019-03-16 13:44:27

标签: ios swift alamofire

我正在尝试使用Alamofire下载文件。为了显示进度,我正在使用alamofire的downloadProgress。我从中得到进度百分比。但是我需要显示到目前为止下载的Mb / Kb总数以及估计的剩余时间。这是我的代码:

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)
                    }
            }

使用通知发布进度

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

使用以下代码显示我的进度

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)
            }
        }

我正在进步。分数完美完成。但是progress.estimatedTimeRemaining,progress.fileCompletedCount和progress.fileTotalCount始终为零。

2 个答案:

答案 0 :(得分:0)

我检查了您可以找到的Progress

open var totalUnitCount: Int64
open var completedUnitCount: Int64

您可以使用这些变量

答案 1 :(得分:0)

简单的 DownloadProgress 类实现,基于来自 Alamofire 或其他的 Progress 和从此处获取的移动平均值 How to estimate download time remaining (accurately)?

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