0

I just added background downloading to my DownloadManager class but I have an issue right now !. For example I just add a file to download , in a table view I have some values like : progress , total bytes written and etc. When I press the home button the downloading will be continue in the background and will be finished but the processing stop there ! and not continue to make process 100% , or change downloaded file size.

The download task method :

func urlSession(_ session: URLSession,
                downloadTask: URLSessionDownloadTask,
                didWriteData bytesWritten: Int64,
                totalBytesWritten: Int64,
                totalBytesExpectedToWrite: Int64){


DispatchQueue.main.async(execute: {() -> Void in

    let db:Double = round(Double(totalBytesExpectedToWrite) / 10000)/100

    //Added by me
    let dbWritten:Double = round(Double(totalBytesWritten) / 10000)/100

    self.fileSize = (NSString(format:"%.2f MB of %.2f MB", dbWritten,db)) as String

    self.downloadProgress = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)
    self.downloadProgressTxt = "\(String(Int(Double(self.downloadProgress*100)))) %";
    self.delegate.updateProgress()

})

}

Start download function :

  func startDownload(){

        let defConfigObject = URLSessionConfiguration.background(withIdentifier: "com.App.backgoundSession")

        let defaultSession = URLSession(configuration: defConfigObject, delegate: self, delegateQueue: OperationQueue())
        downloadTask = defaultSession.downloadTask(with: fileUrl)
        downloadTask.resume()
        downloadStatus = "Downloading"
        isDownloading = true
        delegate.updateProgress()
    }

In app delegate :

 func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
        debugPrint("handleEventsForBackgroundURLSession: \(identifier)")
        completionHandler()
    }

How can I update func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask method when is in the background ?

And I enabled the background mode in capabilities : enter image description here

iOS.Lover
  • 5,923
  • 21
  • 90
  • 162
  • Take a look at this thread for a pretty complete explanation: https://stackoverflow.com/questions/44128358/urlsession-datatask-with-request-block-not-called-in-background – Duncan C Jun 25 '17 at 10:51
  • @DuncanC Thanks but did not help me – iOS.Lover Jun 25 '17 at 13:53

0 Answers0