【问题标题】:Retrieve Alamofire estimatedTimeRemaining & file downloaded size检索 Alamofire 估计剩余时间和文件下载大小
【发布时间】:2019-03-16 13:44:26
【问题描述】:

我正在尝试使用 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.fractionCompleted 完美。但progress.estimatedTimeRemaining、progress.fileCompletedCount 和progress.fileTotalCount 总是为零。

【问题讨论】:

  • 找到解决办法了吗?

标签: ios swift alamofire


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    你查了Progress类你可以找到

    open var totalUnitCount: Int64
    open var completedUnitCount: Int64
    

    你可以使用这些变量

    【讨论】:

    • 我从 totalUnitCount 和 completedUnitCount 得到字节数。你能告诉我如何获得或计算estimatedTimeRemaining?
    • 如果progress.estimatedTimeRemaining 为nil,那就很棘手了,那么您可能会编写自己的逻辑。您已经总计和接收到的字节数,只需计算每个进度之间的时间差并进行自己的计算。但在进行自己的实现之前,只需询问 alamofire 为什么estimatedTimeRemaining 为零
    猜你喜欢
    • 1970-01-01
    • 2011-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-11
    • 2016-07-02
    相关资源
    最近更新 更多