Does NSURLSession for HTTP data task (NSURLSessionDataTask) runs in background thread or we will have to provide the queue?

NSPratik

I started to use NSURLSession by avoiding NSURLConnection now a days as it's a new and elegant API provided by Apple. Previously, I used to put call NSURLRequest in GCD block to execute it in background. Here is how I used to do in past:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    NSURLRequest *request = [NSURLRequest requestWithURL:
                             [NSURL URLWithString:@"www.stackoverflow.com"]];
    NSURLResponse *response;
    NSError *error;
    NSData *data = [NSURLConnection sendSynchronousRequest:request 
                                         returningResponse:&response 
                                                     error:&error];
    if (error) {
        // handle error
        return;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        // do something with the data
    });
});

Now, here is how I use NSURLSession:

- (void)viewDidLoad 
{
    [super viewDidLoad];

    /*-----------------*
        NSURLSession
     *-----------------*/

    NSURLSession *session = [NSURLSession sharedSession];

    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:
                                  [NSURL URLWithString:@"https://itunes.apple.com/search?term=apple&media=software"] 
                                     completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) 
{
    NSDictionary *json = [NSJSONSerialization 
                          JSONObjectWithData:data options:0 error:nil];
    NSLog(@"%@", json);
}];
}

I want to know that, will my request be executed on background thread itself or I will have to provide my own mechanism same way I did in case of NSURLRequest ?

Rob

No, you don't need to use GCD to dispatch this to background queue. In fact, because the completion block runs on background thread, the exact opposite is true, that if you need anything in that block to run on the main queue (e.g., synchronized updates to model objects, UI updates, etc.), you have to manually dispatch that to the main queue yourself. For example, let's imagine that you were going to retrieve a list of results and update the UI to reflect this, you might see something like:

- (void)viewDidLoad 
{
    [super viewDidLoad];

    NSURLSession *session = [NSURLSession sharedSession];

    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:@"https://itunes.apple.com/search?term=apple&media=software"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        // this runs on background thread

        NSError *error;
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];

        // detect and handle errors here

        // otherwise proceed with updating model and UI

        dispatch_async(dispatch_get_main_queue(), ^{
            self.searchResults = json[@"results"];    // update model objects on main thread
            [self.tableView reloadData];              // also update UI on main thread
        });

        NSLog(@"%@", json);
    }];

    [dataTask resume];
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Does NSURLSessionDataTask get paused on background?

From Dev

NSURLSession does not returns data for http/https

From Dev

Converting NSURLSessionDataTask into a Download task with Background support

From Dev

Converting NSURLSessionDataTask into a Download task with Background support

From Dev

NSURLSession background task: avoid duplicates

From Dev

Android: Create a background thread that runs periodically and does UI tasks?

From Dev

Android: Create a background thread that runs periodically and does UI tasks?

From Dev

Uploading Data Using NSURLSession and Queue

From Dev

Does GCD main queue must have to be performed on the main thread?

From Dev

If I want a task to run in the background, how does the "dispatch_get_global_queue" queue work?

From Dev

What effect does precedence have on background task execution?

From Dev

Does Schema.org have actual data or just provide schemas?

From Dev

Does Schema.org have actual data or just provide schemas?

From Dev

Below code runs successfully, so does it mean we can start thread twice?

From Dev

Below code runs successfully, so does it mean we can start thread twice?

From Dev

Does NSURLSession Take place in a separate thread?

From Dev

NSURLSession background transfer : Callback for each video downloaded from a queue

From Dev

NSURLSessionDataTask in background session

From Dev

How to create a task that runs in the background in Android

From Dev

How to guarantee that a Task runs synchronously on the current thread?

From Dev

How to guarantee that a Task runs synchronously on the current thread?

From Dev

How does a queue knows a thread is done without task_done() specified?

From Java

Does Thread.yield() do anything if we have enough processors to service all threads?

From Dev

Does Thread.yield() do anything if we have enough processors to service all threads?

From Dev

Does a class instance thread affinity have any impact on its data?

From Dev

Can we provide data to jasper in paginated fashion?

From Dev

Can we provide data to jasper in paginated fashion?

From Dev

JavaFX background thread task should play music in a loop as background thread

From Dev

Editable queue of tasks running in background thread

Related Related

  1. 1

    Does NSURLSessionDataTask get paused on background?

  2. 2

    NSURLSession does not returns data for http/https

  3. 3

    Converting NSURLSessionDataTask into a Download task with Background support

  4. 4

    Converting NSURLSessionDataTask into a Download task with Background support

  5. 5

    NSURLSession background task: avoid duplicates

  6. 6

    Android: Create a background thread that runs periodically and does UI tasks?

  7. 7

    Android: Create a background thread that runs periodically and does UI tasks?

  8. 8

    Uploading Data Using NSURLSession and Queue

  9. 9

    Does GCD main queue must have to be performed on the main thread?

  10. 10

    If I want a task to run in the background, how does the "dispatch_get_global_queue" queue work?

  11. 11

    What effect does precedence have on background task execution?

  12. 12

    Does Schema.org have actual data or just provide schemas?

  13. 13

    Does Schema.org have actual data or just provide schemas?

  14. 14

    Below code runs successfully, so does it mean we can start thread twice?

  15. 15

    Below code runs successfully, so does it mean we can start thread twice?

  16. 16

    Does NSURLSession Take place in a separate thread?

  17. 17

    NSURLSession background transfer : Callback for each video downloaded from a queue

  18. 18

    NSURLSessionDataTask in background session

  19. 19

    How to create a task that runs in the background in Android

  20. 20

    How to guarantee that a Task runs synchronously on the current thread?

  21. 21

    How to guarantee that a Task runs synchronously on the current thread?

  22. 22

    How does a queue knows a thread is done without task_done() specified?

  23. 23

    Does Thread.yield() do anything if we have enough processors to service all threads?

  24. 24

    Does Thread.yield() do anything if we have enough processors to service all threads?

  25. 25

    Does a class instance thread affinity have any impact on its data?

  26. 26

    Can we provide data to jasper in paginated fashion?

  27. 27

    Can we provide data to jasper in paginated fashion?

  28. 28

    JavaFX background thread task should play music in a loop as background thread

  29. 29

    Editable queue of tasks running in background thread

HotTag

Archive