Search code examples
iosswiftuibuttonuiprogressview

Progressview stop when retouch the UIButton


Here is my situation regarding a iOS app running with Swift.

I have a download button, which start to download a file on touch:

@IBAction func downloadButtonPressed() {
    if let downloadTask = downloadTask {
        downloadTask.cancel()
        statusLabel.text = "HELLO"


    } else {
        statusLabel.text = "Downloading video"
        downloadButton.setTitle("Stop download", for: UIControlState())
        createDownloadTask()

        let urlString = "\(posts[selectedIndexPath].link)"

        DispatchQueue.global(qos: .default).async(execute: {
            //All stuff here

            print("downloadVideo");
            let url=NSURL(string: urlString);
            let urlData=NSData(contentsOf: url! as URL);

            if((urlData) != nil)
            {
                let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]

                let fileName = urlString as NSString;

                let filePath="\(documentsPath)/\(fileName.lastPathComponent)";

                DispatchQueue.main.async(execute: { () -> Void in

                    print(filePath)
                    urlData?.write(toFile: filePath, atomically: true);
                    print("video Saved to document directory of app");
                    self.downloadButton.alpha = 0;
                    self.progressView.alpha = 0;
                    self.cardboardButton.alpha = 1;
                    self.videoButton.alpha = 1;
                })
            }
        })


    }

On touch of the button, i've a small animation hapennign to see how far is the download going using:

 func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        let progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
        progressView.animateProgressViewToProgress(progress)
        progressView.updateProgressViewLabelWithProgress(progress * 100)
//        progressView.updateProgressViewWith(Float(totalBytesWritten), totalFileSize: Float(totalBytesExpectedToWrite))
    }

The problem is If i retouch the download button, the animation stop ! so it bring a feeling that its not downloading the file anymore ! ( but it is still downloading the file).

How could this be fixed ? I'd like ideally that on retouch of the button - nothing happen and the animation of the progressive to keep going...

Thanks a lot for your help and time !


Solution

  • You can set button.isUserInteractionEnabled = false after user touch button and resume it after download ended by setting:

    DispatchQueue.main.async { 
     button.isUserInteractionEnabled = true
    }
    

    As for me it's a simplest way.