I've been traditionally using a pattern where NSOperation subclasses create and manage their own NSURLConnection. The NSOperation subclass is instantiated by the view controller and will do its work without bothering the controller until it has finished. When it finishes retrieving data, it executes the completion block supplied by the view controller.
I'm trying to implement the same pattern with NSURLSession now. I want to be able to encapsulate the url and parameters required to make a network request inside a single object. Do I achieve this using NSURLSession subclasses or NSURLSessionTask subclasses?
I like to create separate classes for every network operation based on the actor design pattern.
You can use the same pattern, replacing NSURLConnection
with NSURLSessionTask
subclasses (e.g. NSURLSessionDataTask
).
As @CouchDeveloper suggests in the comments, an alternative is to wrap NSURLSessionTask
in an non-NSOperation
object with asynchronous semantics (cancel, resume, etc.). This wrapper object would do little more than encode and decode parameters, delegating most operations to the wrapped task.
In either case, to instantiate NSURLSessionTask
, you will need a NSURLSession
. (NSURLSession
is the NSURLSessionTask
factory.) If all of your operations use the same configuration (cookies, proxy, caching, etc.), you can simply use the shared session (+[NSURLSession sharedSession]
). If they need different configurations, you'll have to give them a NSURLSession
or enough information to create their own.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments