将进度条添加到下载文件

时间:2018-07-24 22:06:43

标签: ios swift download progress-bar

我正在实现一个ViewController,以显示以前从服务器下载并本地存储在设备上的PDF,它可以正常工作,但是下载PDF需要太多时间,我想实现一个进度栏

我的代码如下,我在其中尝试实现@IBOutlet weak var downloadBar: UIProgressView!随着下载时间的增加,我吃了代码达到100%并且下载尚未结束的时间。

class PDFViewController: UIViewController {
    @IBOutlet weak var pdfView: PDFView!

    @IBOutlet weak var downloadBar: UIProgressView!

    //*******
    var downloader = Timer()
    var minValue = 0
    var maxValue = 100
    //********

    var namePDF:String?

    override func viewDidLoad() {
        super.viewDidLoad()

        downloadBar.setProgress(0, animated: false)


        if let pdfUrl = URL(string: "https://miserver.com/\(namePDF!).pdf") {


            print(pdfUrl)

            // then lets create your document folder url
            let documentsDirectoryURL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

            // lets create your destination file url
            let destinationUrl = documentsDirectoryURL.appendingPathComponent(pdfUrl.lastPathComponent)
            print(destinationUrl)

            // to check if it exists before downloading it
            if FileManager.default.fileExists(atPath: destinationUrl.path) {
                print("The file already exists at path")

                /************** show pdf ****************/
                let pdfUrl = destinationUrl.path
                let rutafile = URL(fileURLWithPath: pdfUrl)
                print(pdfUrl)
                if let document = PDFDocument(url: rutafile) {
                    pdfView.autoScales = true
                    pdfView.document = document
                }
                 /************** end show pdf ****************/


                // if the file doesn't exist
            } else {
                 print("file doesn't exist")

                downloader = Timer.scheduledTimer(timeInterval: 0.06, target: self, selector: (#selector(PDFViewController.updater)), userInfo: nil, repeats: true)
                downloadBar.setProgress(0, animated: false)

                // you can use NSURLSession.sharedSession to download the data asynchronously
                URLSession.shared.downloadTask(with: pdfUrl, completionHandler: { (location, response, error) -> Void in
                    guard let location = location, error == nil else { return }
                    do {
                        // after downloading your file you need to move it to your destination url
                        try FileManager.default.moveItem(at: location, to: destinationUrl)
                        print("File moved to documents folder")

                        print("file has already been downloaded")
                        /************** show pdf ****************/
                        let pdfUrl = destinationUrl.path
                        let rutafile = URL(fileURLWithPath: pdfUrl)
                        print(pdfUrl)
                        if let document = PDFDocument(url: rutafile) {
                            self.pdfView.autoScales = true
                            self.pdfView.document = document
                        }
                        /************** show pdf ****************/

                    } catch let error as NSError {
                        print(error.localizedDescription)
                    }
                }).resume()
            }
        }



    }

@objc func updater() {

    if minValue != maxValue {
        minValue += 1
        downloadBar.progress = Float(minValue) / Float(maxValue)

        print(Float(minValue) / Float(maxValue))
    } else {
        minValue = 0
        downloader.invalidate()
    }
}

}

非常感谢您

1 个答案:

答案 0 :(得分:1)

您可以实现URLSessionDownloadDelegate协议。然后使用以下方法:

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
    if totalBytesExpectedToWrite > 0 {
        let progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)

        self.downloadBar.setProgress(progress, animated: false)
    }
}

这只会在写入新字节时更新进度条。并准确估算您的下载进度。希望这会有所帮助:)