Search code examples
iosswiftnsurlsessionurlsession

`URLSessionDelegate` methods are not called


Please, note that I've checked previous answers and I am not using callbacks in the code. In this case the delegate methods should be called

Environment iOS 14.4.2

URL is valid. File is downloaded. Just the delegate not get called.

The example code is below:

final class Downloader: NSObject, URLSessionDelegate {

    private lazy var urlSession = URLSession(
        configuration: .default,
        delegate: self,
        delegateQueue: .main
    )
    private var downloadTask: URLSessionDownloadTask?

    func beginDownload(url: URL) {
        downloadTask = urlSession.downloadTask(with: url)
        downloadTask!.resume()
    }

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        // NEVER CALLED
    }
}

Solution

  • The func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) method you're implementing is part of URLSessionDownloadDelegate, not URLSessionDelegate, so you should declare conformance to URLSessionDownloadDelegate as well in order for the delegate call to occur.