Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URLSessionDelegate Function Not Being Called

I would like to process data as it comes in, so I've instiated a URL session like so:

let session = URLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: operationQueue);

I also set the class to be a URLSessionDataDelegate:

class ViewController: UITableViewController, URLSessionDataDelegate{

Lastly, I implement the didReceive data function like this:

func urlSession(_ session: URLSession,
                dataTask: URLSessionDataTask,
                didReceive data: Data){
    print(data)
}

However, the function is never being called.

I run my session like this:

let session1 = session.dataTask(with: url) { (data, response, error) in
    print(data!);
}

It prints the data from the callback, but not from the delegate. Any help is greatly appreciated.

EDIT: I also added the following:

func urlSession(_ session: URLSession,
                dataTask: URLSessionDataTask,
                didReceive response: URLResponse,
                completionHandler: @escaping (URLSession.ResponseDisposition) -> Void){
    completionHandler(URLSession.ResponseDisposition.allow);
}

However, the delegate method is still not being called.

like image 675
Dan Avatar asked May 29 '17 10:05

Dan


1 Answers

The reason this is not working is that you're creating your data task with a completion handler. Instead you must use the dataTask(with:) function instead.

I also missed this in the documentation and spent hours wondering why my delegate methods weren't being called.

From the docs:

By using the completion handler, the task bypasses calls to delegate methods for response and data delivery, and instead provides any resulting NSData, URLResponse, and NSError objects inside the completion handler. Delegate methods for handling authentication challenges, however, are still called.

like image 72
Ben Baron Avatar answered Nov 15 '22 11:11

Ben Baron