URLSession委托未调用的成功方法,但没有错误

时间:2017-01-02 14:25:51

标签: ios nsurlsessiondownloadtask urlsession

我使用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

提前谢谢。

1 个答案:

答案 0 :(得分:1)

您应该使用git push . refs/remotes/remote1/*:refs/heads/* 代替URLSessionDownloadTask,并使用URLSessionDataTask的背景,如下所示:

URLSessionConfiguration