I want to execute two requests to my remote server and get and parse two response asynchronously, but still block the main thread until both of two processes are done.
Here's my code in AppDelegate.m's application: didFinishLaunchingWithOptions:
method:
NSURL *url1 = [NSURL URLWithString: @"url1"];
NSURL *url2 = [NSURL URLWithString:@"url2"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task1 = [session dataTaskWithURL:url1 completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//process1
}];
[task1 resume];
NSURLSessionDataTask *task2 = [session dataTaskWithURL:url2 completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//process2
}];
[task2 resume];
In this code, I want to fetch data from url1
and parse the response in process1
, and also want to do the same thing to url2
and process2
.
However, while I want to execute those two processes above asynchronously, I also want to wait for both to finish each work before ending AppDelegate.m
's application: didLaunchingWithOptions:
method, because an error happens in my first view controller (after AppDelegate.m) if it's initialized before the above two execution are done.
This is easily implemented in some languages such as Python or Go, and I think it can also be implemented in NSURLConnection
in Objective-C (though I didn't try, forgive me if it's not the case). However, I want to use NSURLSession
in this case, since the actual session configuration is a bit more complicated than the code above.
So is it feasible to use synchronous feature in NSURLSession
?