iosswiftdelegatesnsurlsessiondownloadtask

How to delegate URLSessionDownloadDelegate


I have implemented this code that download a files from remote I want to create progress bar but Delegate not works.

Can you help me to understand the problem for this issue?

Thanks a lot to all

import UIKit

class ViewController: UIViewController, URLSessionDownloadDelegate{
    
    var downloadSession: URLSession?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        downloadSession = URLSession(configuration: .default, delegate: self,
                                     delegateQueue: OperationQueue.main)
        
        
        guard let url = URL(string: "http://filedownload") else { return }
        let task = self.downloadSession?.downloadTask(with: url, completionHandler: {
            (URL, response, error) -> Void in
            
            
        })
        
        task?.resume()
    }
    
    
    
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        
    }
    
    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        if totalBytesExpectedToWrite > 0 {
            
            
        }
    }
    
}

Solution

  • In order for the delegate methods to be called you need to remove the completion handler:

    let task = self.downloadSession?.downloadTask(with: url)