3

我正在使用 URLSession dataTask 下载带有 URLSessionDownloadDelegate 作为结果处理程序的文件。但是,urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL)从不调用。相反,我得到urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)的错误为零。当使用 completionHandler 方法来执行任务时,一切正常。

这是我的代码:

import UIKit

class ViewController: UIViewController, URLSessionDownloadDelegate {

var downloadTask: URLSessionDataTask?

override func viewDidLoad() {
    super.viewDidLoad()

    let configuration = URLSessionConfiguration.default
    let session = URLSession(configuration: configuration, delegate: self, delegateQueue: OperationQueue.main)

    let url = URL(string: "https://unsplash.it/200/300/?random")!
    //downloadTask = session.dataTask(with: request)
    downloadTask = session.dataTask(with: url)
    downloadTask!.resume()
}


@IBAction func cancelButtonTapped(_ sender: Any) {
    downloadTask?.cancel()
}

func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
    print("session: didBecomeInvalidWithError: \(error?.localizedDescription)")
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
    print("Your data is here!")
}

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
    let progress = Float(totalBytesWritten / totalBytesExpectedToWrite)
    print("Making progress: \(progress)")
}

func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
    print("session: task: didCompleteWithError: \(error?.localizedDescription)")
    session.finishTasksAndInvalidate()
}

}

模拟器输出是

session: task: didCompleteWithError: nil
session: didBecomeInvalidWithError: nil

先感谢您。

4

1 回答 1

1

您应该使用URLSessionDownloadTask而不是URLSessionDataTask使用背景,URLSessionConfiguration如下所示:

var downloadTask: URLSessionDownloadTask?
var session: URLSession?

override func viewDidLoad() {
        super.viewDidLoad()


        let configuration = URLSessionConfiguration.background(withIdentifier: "backgroundSession")
        session = URLSession(configuration: configuration, delegate: self, delegateQueue: OperationQueue.main)

        let url = URL(string: "https://unsplash.it/200/300/?random")!
        downloadTask = session?.downloadTask(with: url)
        downloadTask!.resume()

}
于 2017-01-03T01:29:47.050 回答