Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

ios - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...