swift - 下载百分比 (SWIFT)
问题描述
我想在标签中获得下载百分比。我使用此代码
self.percentageLabel.text = "\(Int(percentage * 100))%"
但问题是这样显示的数字(-90043%)
任何想法 ?
这是我的完整代码
import UIKit
class ViewController: UIViewController, URLSessionDownloadDelegate {
let shapeLayer = CAShapeLayer()
let percentageLabel: UILabel = {
let label = UILabel()
label.text = ""
label.textAlignment = .center
label.font = UIFont.boldSystemFont(ofSize: 32)
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
view.addSubview(percentageLabel)
percentageLabel.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
percentageLabel.center = view.center
let trackLayer = CAShapeLayer()
let circularPath = UIBezierPath(arcCenter: .zero, radius: 100, startAngle: 0, endAngle: 2 * CGFloat.pi, clockwise: true)
trackLayer.path = circularPath.cgPath
trackLayer.strokeColor = UIColor.white.cgColor
trackLayer.lineWidth = 0.2
trackLayer.fillColor = UIColor.clear.cgColor
trackLayer.lineCap = CAShapeLayerLineCap.round
trackLayer.position = view.center
view.layer.addSublayer(trackLayer)
shapeLayer.path = circularPath.cgPath
shapeLayer.strokeColor = UIColor.yellow.cgColor
shapeLayer.lineWidth = 10
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.lineCap = CAShapeLayerLineCap.round
shapeLayer.position = view.center
shapeLayer.transform = CATransform3DMakeRotation(-CGFloat.pi/2, 0, 0, 1)
shapeLayer.strokeEnd = 0
view.layer.addSublayer(shapeLayer)
view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap)))
}
let urlString = UIPasteboard.general
private func beginDownloadingFile()
{
print("Downloading Started ... ")
self.shapeLayer.strokeEnd = 0
let configuration = URLSessionConfiguration.default
let operationQueue = OperationQueue()
let urlSession = URLSession(configuration: configuration, delegate: self, delegateQueue: operationQueue)
if let urlString = urlString.string {
print(urlString)
guard let url = URL(string: urlString) else {
print("URL Not valid")
return
}
let downloadTask = urlSession.downloadTask(with: url)
downloadTask.resume()
}
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
print("Finshed Downloading Files")
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
print("TotalBytes:- ", totalBytesWritten, "and toBytesWrittenExpected:- ", totalBytesExpectedToWrite)
let percentage = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
print("percentage : ", percentage)
DispatchQueue.main.async {
self.shapeLayer.strokeEnd = CGFloat(percentage)
self.percentageLabel.text = "\(Int(percentage * 100))%"
self.percentageLabel.font = UIFont.boldSystemFont(ofSize: 20)
self.percentageLabel.textColor = UIColor.white
}
print("Percentage Downloaded:- ", percentage)
}
fileprivate func animateCircle() {
let basicAnimation = CABasicAnimation(keyPath: "strokeEnd")
basicAnimation.toValue = 1
basicAnimation.duration = 2
basicAnimation.fillMode = CAMediaTimingFillMode.forwards
basicAnimation.isRemovedOnCompletion = false
shapeLayer.add(basicAnimation, forKey: "urSoBasic")
}
@objc private func handleTap(){
print("Do Animation")
beginDownloadingFile()
}
}
解决方案
您的代码看起来正确。所以问题在于 和 的totalBytesWritten
值totalBytesExpectedToWrite
。
如果totalBytesWritten
= 9453 和totalBytesExpectedToWrite
= -1 则无法计算百分比。
基本上你必须确保传入的值totalBytesExpectedToWrite
是正确的。
来自 Apple 文档URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:
文件的预期长度,由 Content-Length 标头提供。如果未提供此标头,则值为
NSURLSessionTransferSizeUnknown
(-1)。
正如评论中所建议的,您可以尝试这个解释来尝试解决totalBytesExpectedToWrite
= -1
推荐阅读
- python - 将 bqplot 工具提示与数据框一起使用
- sql - 创建两个外键相互引用的表
- mongodb - 在 MongoDB 中通过 ObjectId 而不是 image_name 获取图像
- c++ - 如何更改此代码以使用 100 个对象的数组?
- reactjs - 未捕获(承诺中)ReferenceError:数据未在反应组件中定义
- linux - 如何使用字符串分隔符将标准错误重定向到标准输出
- c# - C# 代码中的数据绑定控件(.cs 文件)
- xcode - Xcode 11 Export for Localization 不起作用,Include Screenshots 功能被禁用,并且在测试日志中找不到 XCUITest 屏幕截图附件
- azure - Azure 公共 IP 的多个 FQDN 或 DNS
- sql-server - 删除无效行以添加外键约束?