ios - 使用 Alamofire 的下载速率
问题描述
我正在使用此功能编写一个带有 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
}
解决方案
我不认为 Alamofire 或任何其他库提供下载速度。开发人员必须自己计算。你可以这样做:
- 取一个保存先前下载字节的全局变量。
- 使用
NSTimer
1 秒间隔计算速度。
代码示例:
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
}
推荐阅读
- php - 如何修复 WordPress 中的错误:“标签必须配对,没有开始标签:[]”?
- linux - Bash 如何根据大小移动文件夹
- visual-studio - 更改 Workspace Visual Sudio 2019 的计算机名称
- linux - 为什么名称是accept4 而不是accept1,就像epoll_create1 for epoll_create 一样?
- python - 在Python中过滤具有条件的对象列表
- 32bit-64bit - 当 32 位用户在 64 位上时如何处理 ioctl 调用
- javascript - 为什么我的 Wordpress Timber 组件会破坏页面?
- c++ - 将许多图像加载到 OpenGL 中并将它们渲染到屏幕上
- javascript - 从 Handlebars 调用变量到 HTML
- css - 当输入字段(同一元素的子元素)占位符文本被隐藏时修改元素的 ::after