2

In my application, I need to download a file(size:50mb), also I need to support background downloading. By the following code I can do the download even in the background. The only problem is UI is not updating properly when I tried to switch the app (say I open WhatsApp) and come back to my app without going to iPhone's Home Screen.

I debugged the code, I found didWriteData is not called.

weak var downloadTask: URLSessionDownloadTask?
lazy var downloadSession: URLSession = {
        let configuration = URLSessionConfiguration.background(withIdentifier: "MYDOWNLOADIDENTIFIER")
        return URLSession(configuration: configuration,
                          delegate: self,
                          delegateQueue: OperationQueue.main)
    }()

Download Pressed Event:

downloadTask = self.downloadSession.downloadTask(with: fileUrl)
 downloadTask?.resume()


func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
    //UI update for progress level
    }

func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
        logger.write("urlSessionDidFinishEvents\n")
        DispatchQueue.main.async {
            if let appDelegate = UIApplication.shared.delegate as? AppDelegate,
                let completionHandler = appDelegate.backgroundSessionCompletionHandler {
                appDelegate.backgroundSessionCompletionHandler = nil
                completionHandler()
            }
        }
    }

AppDelegate.swift

  func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
        backgroundSessionCompletionHandler = completionHandler
    }
Sridhar
  • 2,228
  • 10
  • 48
  • 79
  • 1
    It's a long-standing issue https://stackoverflow.com/a/57120558 – paiv Apr 21 '21 at 15:48
  • Since the process that handles the download is a different one than the actual app itself, it eventually doesnt update your app with the progress, as more likely it is not dowloading your stuff at that moment. (Maybe because you switched apps, and system thinks to resume your downloads at a later time). "urlSessionDidFinishEvents" instead is called at the end, when all ongoing requests have finished (or errored out). – Sardorbek Ruzmatov Apr 27 '21 at 07:51
  • To "resume" progress on your app you could 1) stop the ongoing task by copying what is has downloaded so far to a variable, and 2) launch another new task with that blob. – Sardorbek Ruzmatov Apr 27 '21 at 07:58

0 Answers0