Danny Bravo Danny Bravo - 1 month ago 36
iOS Question

urlSession:dataTask:didReceive:completionHandler not called in Xcode8 Swift3

I've created a background

URLSession
object using the following code:

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


I've also implemented the following
URLSessionDataDelegate
methods in the delegate class:

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
}


I'm able to successfully call
URLSessionUploadTask
from this session using the following:

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


But for some reason I only get callbacks for:

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


and

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


The delegate method:

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


never gets called.

Is this a bug in Xcode8 or am I missing something important?
Thanks for the help!

Answer

Direct quote from Apple SDK regarding this method:

/*
 * 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;

Edit: added more context to a quote

Comments