'How to put the file download progress on the label on the MacOS App interface using Swift?
I write a download button that works fine, but can't show the percentage progress on the label.
I tried putting the label in the FileDownloader class, but it's not updating and showing on the interface.
0.041681744
0.045944795
0.11841663
0.12694274
0.13546883
.
.
.
99.66489
99.84393
99.84819
100.0
this is my code:
class ramdisk: NSViewController {
...
class FileDownloader : NSObject, URLSessionDownloadDelegate {
var url : URL?
// will be used to do whatever is needed once download is complete
var yourOwnObject : NSObject?
init(_ yourOwnObject : NSObject)
{
self.yourOwnObject = yourOwnObject
}
//is called once the download is complete
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL)
{
//copy downloaded data to your documents directory with same names as source file
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
//FileManager.default.
let destinationUrl = documentsUrl!.appendingPathComponent(url!.lastPathComponent)
let dataFromURL = NSData(contentsOf: location)
dataFromURL?.write(to: destinationUrl, atomically: true)
//now it is time to do what is needed to be done after the download
//yourOwnObject!.callWhatIsNeeded()
}
//this is to track progress
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
let progress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
let progressPercentage = progress * 100
print(progressPercentage)
}
// if there is an error during download this will be called
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
{
if (error != nil)
{
//handle the error
print("Download completed with error: \(error!.localizedDescription)");
}
}
//method to be called to download
func download(url: URL)
{
self.url = url
//download identifier can be customized. I used the "ulr.absoluteString"
let sessionConfig = URLSessionConfiguration.background(withIdentifier: url.absoluteString)
let session = Foundation.URLSession(configuration: sessionConfig, delegate: self, delegateQueue: nil)
let task = session.downloadTask(with: url)
task.resume()
}
}
@IBAction func downloads(_ sender: Any) {
let strURL = "http://downloads.xyz/test.zip"
let url = URL(string: strURL)
FileDownloader(url! as NSObject).download(url: url!)
}
...
}
I write a download button that works fine, but can't show the percentage progress on the label.
I tried putting the label in the FileDownloader class, but it's not updating and showing on the interface.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
