13

I was designing an app that uses NSURLSession and thinking about putting it in a different thread with Grand Central Dispatch, but if NSURLSession automatically does that in the background, I wouldn't have to use GCD then, correct?

So in other words, does NSURLSession automatically use Grand Central Dispatch in the background, so we don't have to worry about it?

pwoerfulafhjksdh
  • 381
  • 1
  • 3
  • 11

2 Answers2

21

Yes,

NSURLSession (URLSession in Swift) does its work in a background thread. The download ALWAYS takes place asynchronously on a background thread.


EDIT:

There is no reason to wrap your code that invokes NSURLSession (or URLSession in Swift 3 or later) in a GCD call.


You can control whether its completion methods are executed on a background thread or not by the queue you pass in in the delegateQueue parameter to the init method. If you pass in nil, it creates a (background thread) serial operation queue where your completion methods are called. If you pass in NSOperationQueue.mainQueue() (OperationQueue.mainQueue() in recent versions of Swift) then your completion delegate methods/closures will be invoked on the main thread and you won't have to wrap UI calls in dispatch_async() calls to the main thread.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
3

Here's an example of an NSURLSession request:

[[session dataTaskWithURL:[NSURL URLWithString:someURL]
      completionHandler:^(NSData *data,
                          NSURLResponse *response,
                          NSError *error) {
        // handle response

  }] resume];

From the Documentation: "This method is intended as an alternative to the sendAsynchronousRequest:queue:completionHandler: method of NSURLConnection, with the added ability to support custom authentication and cancellation." Short answer is: yes, NSURLSession will do background operations. You don't have to worry about this blocking your UI.

erparker
  • 1,301
  • 10
  • 21
  • Your answer is about the deprecated NSURLConnection. But the question is about NSURLSession. – Fogmeister Jun 15 '15 at 20:45
  • Updated my answer to NSURLSession – erparker Jun 15 '15 at 20:47
  • Background operations are a different thing. `NSURLSession` always uses a background thread to transfer your data from the remote device. When the docs on `NSURLSession` talk about background, they are talking about having your download/data task continue even if your app is in the background, suspended, or even terminated. – Duncan C Nov 02 '16 at 11:36