Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 添加进度条以下载文件_Ios_Swift_Download_Progress Bar - Fatal编程技术网

Ios 添加进度条以下载文件

Ios 添加进度条以下载文件,ios,swift,download,progress-bar,Ios,Swift,Download,Progress Bar,我正在实现一个ViewController来显示以前从服务器下载并存储在设备本地的PDF,它工作正常,但下载PDF需要花费太多时间,我想实现一个进度条 我的代码如下,在这里我尝试实现@IBOutlet弱var下载栏:UIProgressView。 当我得到下载所需的时间时,我会吃掉100%的代码,下载还没有结束。 class PDFViewController: UIViewController { @IBOutlet weak var pdfView: PDFView! @I

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

我的代码如下,在这里我尝试实现
@IBOutlet弱var下载栏: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()
    }
}
}


非常感谢您

您可以实现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)
    }
}

这将仅在写入新字节时更新进度条。并提供下载进度的准确估计。希望这有帮助:)

为什么要使用计时器?var downloader=Timer()。您是否也面临IBOutlet的问题,或者进度没有显示?当您想要显示进度时,调用
downloadTask(with:completionHandler:)
for
shared
并不是最好的方法。创建一个配置了委托的
URLSession
并正确准备委托方法,然后对创建的实例使用
downloadTask(with:)
。我没有足够的时间写一个答案,希望你能很快找到正确的方向。@Asim Progress如果它被显示(进度条工作),但我的问题是它在没有完成下载文件的情况下达到100的时间。如何获得下载所需的时间?如何使用此URLSessionDownoadDelegate协议?我的意思是哪一类应该符合它?您能给出一个详细的答案吗?只需将协议与您从中调用它的类相一致,例如您要更新进度的相应ViewController。并听取上述功能的进展情况。每次进行进度时都会调用该函数,您可以将更新的进度分配给进度条。