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), ^{
NSURL *url = [NSURL URLWithString:@"www.stackoverflow.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
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
*-----------------*/
NSURL *url = [NSURL URLWithString:@"https://itunes.apple.com/search?term=apple&media=software"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url
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
?
sendAsynchronousRequest
runs in background despite we don't provide any background queue... – ConcertmasterNSURLSession
code block into GCD queue to make it run in background ? Please refer to my code block written in question itself.. – ConcertmasterNSURLSession
methods. The geocoder and the location search methods. Many of the Cocoa methods that are doing something asynchronously and have completion blocks/closures do so on background thread. – Petrolatum