简体   繁体   English

如何将委托更改为NSURLSession

[英]How to change delegate to NSURLSession

I am using NSURLSession for server communication. 我正在使用NSURLSession进行服务器通信。 I am having 2 class individually for Downloading and uploading files. 我分别有2节课用于下载和上传文件。 I want to use Single NSURLSession for downloading and uploading operation. 我想使用Single NSURLSession进行下载和上传操作。 In such I can't change the delegate for NSURLSession at run time by using setDelegate option, since I'm using Delegates to validate data. 在这种情况下,我无法在运行时使用setDelegate选项更改NSURLSession的委托,因为我正在使用委托来验证数据。 Is there any way to change delegate object for NSURLSession at run time? 有什么方法可以在运行时更改NSURLSession的委托对象吗?

Thanks. 谢谢。

The delegate cannot be changed. delegate不能更改。 It is the delegate that was "assigned when this object was created." 是“在创建此对象时分配的”委托。 And as the documentation goes on to say: 随着文档的继续说:

Note: 注意:

This delegate object must be set at object creation time and may not be changed. delegate对象必须在对象创建时设置,并且不能更改。

So, you'll have to design a delegate object that can differentiate between your various network tasks, handling each appropriately. 因此,您必须设计一个可以区分各种网络任务的委托对象,并适当地处理每个任务。

You could, theoretically, create separate delegate objects, and maintain a dictionary, keyed by the task identifier, of pointers to secondary delegate objects. 从理论上讲,您可以创建单独的委托对象,并维护一个以任务标识符为关键字的字典,该字典包含辅助委托对象的指针。 You can then write a delegate for the NSURLSession that, for the task delegate methods, looked up the task identifier in its dictionary, calling the appropriate method in the appropriate delegate object. 然后,您可以为NSURLSession编写一个委托,对于任务委托方法,该委托在其字典中查找任务标识符,并在适当的委托对象中调用适当的方法。 But this is a bit inelegant, so you should probably stop and ask yourself if there are simpler ways to solve the problem. 但这有点不雅致,因此您可能应该停下来,问问自己是否有解决问题的更简单方法。

As Rob says, you can't change the delegate of an NSURLSession. 正如Rob所说,您不能更改NSURLSession的委托。

You have a few other options. 您还有其他选择。

  • You can set up a download manager object (probably a singleton) that manages the NSURLSession and is it's delegate, and have it forward messages to whatever object requested the upload or download. 您可以设置一个下载管理器对象(可能是一个单例),该对象管理NSURLSession及其委托,并将其转发消息到请求上传或下载的任何对象。

  • You can create multiple instances of NSURSession, one for uploading and one for downloading, each with a separate delegate. 您可以创建多个NSURSession实例,一个实例用于上传,一个实例用于下载,每个实例都有一个单独的委托。 (You said you don't want to do that, but you should revisit that option. (您说过不想这样做,但是您应该重新考虑该选项。

  • You can use the NSURLSession methods that pass a completion handler rather than using a delegate.. 您可以使用传递完成处理程序的NSURLSession方法,而不使用委托。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM