首页 > 解决方案 > 下载百分比 (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()

    }

}

标签: swift

解决方案


您的代码看起来正确。所以问题在于 和 的totalBytesWrittentotalBytesExpectedToWrite

如果totalBytesWritten= 9453 和totalBytesExpectedToWrite= -1 则无法计算百分比。

基本上你必须确保传入的值totalBytesExpectedToWrite是正确的。

来自 Apple 文档URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:

文件的预期长度,由 Content-Length 标头提供。如果未提供此标头,则值为 NSURLSessionTransferSizeUnknown(-1)。

正如评论中所建议的,您可以尝试这个解释来尝试解决totalBytesExpectedToWrite= -1


推荐阅读