KPZZSS
KPZZSS

Reputation: 31

How to change delegate to NSURLSession

I am using NSURLSession for server communication. I am having 2 class individually for Downloading and uploading files. I want to use Single NSURLSession for downloading and uploading operation. 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. Is there any way to change delegate object for NSURLSession at run time?

Thanks.

Upvotes: 2

Views: 3577

Answers (2)

Rob
Rob

Reputation: 437552

The delegate cannot be changed. 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.

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. But this is a bit inelegant, so you should probably stop and ask yourself if there are simpler ways to solve the problem.

Upvotes: 2

Duncan C
Duncan C

Reputation: 131418

As Rob says, you can't change the delegate of an 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.

  • You can create multiple instances of NSURSession, one for uploading and one for downloading, each with a separate delegate. (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..

Upvotes: 2

Related Questions