What is the best practices for reusing NSURLSessions
? From what I can tell, it seems that as long as the configuration (timeouts, caching policies, etc.) does not need to change, there is no need to create a new one (since you can spawn new tasks from it).
So can a single NSURLSession
be reused for an entire app? Per domain/endpoint? Per request?
Overview. The NSURLSession class and related classes provide an API for downloading data from and uploading data to endpoints indicated by URLs. Your app can also use this API to perform background downloads when your app isn't running or, in iOS, while your app is suspended.
An NSURLConnection object handles a single request and any follow-on requests. An NSURLSession object manages multiple tasks, each of which represents a single URL request and any follow-on requests. With NSURLConnection, each connection object has a separate delegate.
If you don't invalidate the session, your app leaks memory until the app terminates. Each task you create with the session calls back to the session's delegate, using the methods defined in URLSessionTaskDelegate .
NSURLSession introduces a new pattern to Foundation delegate methods with its use of completionHandler: parameters. This allows delegate methods to safely be run on the main thread without blocking; a delegate can simply dispatch_async to the background, and call the completionHandler when finished.
Checkout the docs. Specifically "Like most networking APIs, the NSURLSession API is highly asynchronous."
You can always create a networking class that specifically handles all of your networking for the app. So reusing is not only an option but is also recommended.
https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSession_class/
Here is a pretty good tut that explains the differences between NSURLSession and NSULConnection for better understanding of it's intended usage.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With