Is NSURLSession running in a separate thread?

I was developing an application using NSURLSession, and was thinking of putting it on another thread using Grand Central Dispatch, but if NSURLSession does this automatically in the background, I won’t need to use GCD then, right?

In other words, NSURLSession automatically uses Grand Central Dispatch in the background, so we don’t need to worry about that?

+6
source share
2 answers

Yes,

NSURLSession does its job in the background thread. Download is ALWAYS performed in the background thread.

You can control whether its completion methods are executed in the background thread or not in the queue that you pass in the delegateQueue parameter to the init method. If you go to zero, it creates the next operational queue (background thread), in which your termination method is called. If you pass in NSOperationQueue.mainQueue() , then your completion delegate methods will be called in the main thread, and you won’t have to transfer the UI calls to dispatch_async() calls in the main thread.

+14
source

Here is an example 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 sendAsynchronousRequest: queue: completeHandler: method NSURLConnection, with the added ability to support user authentication and cancellation." Short answer: yes, NSURLSession will perform background operations. You do not need to worry about this by blocking your user interface.

+3
source

Source: https://habr.com/ru/post/989158/


All Articles