iOS | URLSession | Download task| didWriteData not calling when user switch between apps and come

687 Views Asked by At

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
    }
0

There are 0 best solutions below