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 ?