10

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?

Andy Hin
  • 30,345
  • 42
  • 99
  • 142
  • 2
    @matt This seems like a perfectly valid question. E.g. are there any cases when an `NSURLSession` becomes invalid? In [Life Cycle of a URL Session](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/URLLoadingSystem/NSURLSessionConcepts/NSURLSessionConcepts.html#//apple_ref/doc/uid/10000165i-CH2-SW2) it says "reassociate with the session if your app crashes or is terminated or suspended" - in particular that last point - if my app is suspended, do I need to do anything when it resumes? (That quote is about background sessions, but it's illustrative of the ambiguity) – CupawnTae Sep 04 '17 at 14:20

1 Answers1

3

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.

Mark McCorkle
  • 9,349
  • 2
  • 32
  • 42