URLSessionDataDelegate方法未被调用

时间:2018-12-15 21:21:00

标签: swift urlsession

我正在视图控制器中开始下载会话:

class MyController: UIViewController {
  func startDownload(withURL url: URL) {
    downloadSession = URLSession(configuration: URLSessionConfiguration.default,
                                      delegate: self,
                                 delegateQueue: OperationQueue.main)
    downloadTask = downloadSession.dataTask(with: url)
    downloadTask.resume()
  }
}

委托方法在扩展中定义:

extension MyController: URLSessionDelegate {
  func urlSession(_ session: URLSession, 
                   dataTask: URLSessionDataTask, 
            didReceive data: Data) {
     ...
  }

  func urlSession(_ session: URLSession, 
                       task: URLSessionTask, 
    didCompleteWithError error: Error?) {
     ... 
  }
}

为什么从来不调用这些委托方法?

1 个答案:

答案 0 :(得分:0)

您只能在扩展名中声明符合URLSessionDelegate。如果改为声明符合URLSessionDataDelegate,则将调用您的委托方法。