URLSessionDelegate函数未调用 [英] URLSessionDelegate Function Not Being Called

查看:172
本文介绍了URLSessionDelegate函数未调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想处理传入的数据,因此我启动了一个URL会话,如下所示:

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);

我还将类设置为URLSessionDataDelegate:

I also set the class to be a URLSessionDataDelegate:

class ViewController: UITableViewController, URLSessionDataDelegate{

最后,我实现了didReceive数据函数,如下所示:

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.

我这样运行我的会话:

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.

我还添加了以下内容:

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.

推荐答案

不起作用的原因是您正在使用完成处理程序创建数据任务.相反,您必须改为使用dataTask(with:)函数.

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.

从文档中

通过使用完成处理程序,任务将绕过对委托方法的调用以进行响应和数据传递,而是提供任何结果 完成处理程序中的NSData,URLResponse和NSError对象.但是,仍然调用用于处理身份验证挑战的委托方法.

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.

这篇关于URLSessionDelegate函数未调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆