Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to create new NSURLSession?

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?

like image 379
Andy Hin Avatar asked Apr 14 '15 15:04

Andy Hin


People also ask

What is NSURLSession how is it used?

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.

What is difference between NSURLConnection and NSURLSession?

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.

What will happend if you don't invalidate the session URLSession explicitly?

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 .

How do I use NSURLSession in Objective C?

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.


1 Answers

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.

like image 191
Mark McCorkle Avatar answered Oct 02 '22 07:10

Mark McCorkle