urlSession:dataTask:didReceive:在Xcode8 Swift3中没有调用completionHandler

时间:2016-11-02 11:26:22

标签: ios swift3 xcode8

我使用以下代码创建了一个后台URLSession对象:

let identifier = /* some background identifier */
let config = URLSessionConfiguration.background(withIdentifier: identifier)
self.session = URLSession(configuration: config, delegate: self, delegateQueue: nil)

我还在委托类中实现了以下URLSessionDataDelegate方法:

public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
    // code goes here
}

public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
    // code goes here
}

public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { 
    // code goes here
}

我可以使用以下内容从此会话成功呼叫URLSessionUploadTask

let fileURl = /* some file url */
let request = /* some URLRequest */
let task = session.uploadTask(with: request, fromFile: fileUrl)
task.resume()

但出于某种原因,我只收到回调:

`urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)` 

`urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data)`.

委托方法:

`urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void)`

永远不会被召唤。

这是Xcode8中的错误还是我错过了重要的内容? 谢谢你的帮助!

1 个答案:

答案 0 :(得分:3)

Apple SDK直接引用此方法:

/*
 * Messages related to the operation of a task that delivers data
 * directly to the delegate.
 */
@protocol NSURLSessionDataDelegate <NSURLSessionTaskDelegate>
@optional
/* The task has received a response and no further messages will be
 * received until the completion block is called. The disposition
 * allows you to cancel a request or to turn a data task into a
 * download task. This delegate message is optional - if you do not
 * implement it, you can get the response as a property of the task.
 *
 * This method will not be called for background upload tasks (which cannot be converted to download tasks).
 */
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
                                 didReceiveResponse:(NSURLResponse *)response
                                  completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler;

编辑:为报价添加了更多上下文