在后台下载文件和URLSessionDownloadTask

时间:2017-06-25 10:21:40

标签: ios iphone swift xcode nsurlsession

我刚刚将后台下载添加到我的DownloadManager课程中,但我现在有一个问题!例如,我只是添加一个要下载的文件,在表格视图中我有一些值,如:progresstotal bytes written等。当我按下主页按钮时,下载将在后台继续,并将完成但处理停在那里!而不是继续100%进程,或更改下载的文件大小。

下载任务方法:

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()

})

}

开始下载功能:

  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()
    }

在app delegate:

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

如何在后台更新func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask方法?

我在功能中启用了后台模式: enter image description here

0 个答案:

没有答案