Search code examples
iosswiftuiprogressview

how to still show the progress of progressView after reloading the view controller?


this is my first question on swift, i couldn't really find any answer in the internet. i have a download button that download a pdf file from url, and there is a progressView that shows the progress of downloading to the user. everything works fine but when i download the file and reload the view controller the progress of progressView is resets to zero. how can i still show the progress of downloading even after reloading the viewController.

I'm passing the url from another viewController

please help me.

this is my code

class CellDetailsViewController: UIViewController , URLSessionDownloadDelegate{

    var download = ""
    var downloadTask : URLSessionDownloadTask!

   override func viewDidLoad() {
        super.viewDidLoad()

    }

    @IBAction func download(_ sender: Any) {
        guard let url = URL(string: download)else {return}
        let urlSession = URLSession(configuration: .default, delegate: self, delegateQueue: OperationQueue())
         downloadTask = urlSession.downloadTask(with: url)
        downloadTask.resume()
        print("downloading")
    }


    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        print("download Location", location)
        let fileManager = FileManager.default
        let documentPath = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
        let PdfName = documentPath.appendingPathComponent("\(name).pdf")
        try? fileManager.removeItem(at: PdfName)
        do{
            try fileManager.moveItem(at: location, to: PdfName)
        }catch{
            print("copy error\(error.localizedDescription)")
        }
    }


    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        
        if totalBytesExpectedToWrite > 0 {
            let progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
            DispatchQueue.main.async {
                self.progressView.progress = progress
                print(totalBytesExpectedToWrite)
                if progress == 1 {
                    self.progressView.isHidden = true
                }
            }
        }
    }

}

Solution

  • You can store a static variable in a struct somewhere else. I would create a new file that you can store in a "Model" folder and do something like this:

    struct staticVariableStorage {
    static var fileProgress : Double = 0.0 }
    

    and then you could access it in your code by setting a new value to

    staticVariableStorage.fileProgress
    

    This shouldn't be affected by resetting the ViewController seeing as it would be separate from the ViewController in the first place.