Question

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?

Was it helpful?

Solution

Why would you block the main thread?? This is bad for users, and bad for you.

Change your view controller to show a progress indication instead of crash. This keeps the app active and the user informed of what is happening. If you want you can have a nice animation for the user to watch while they wait.

OTHER TIPS

Its a bad idea to block application launch, it will crash the app if the app didn't launch in launchTime <=24 seconds. If your doesn't lanuch within it will kill the app. So what you should do then. Use your own loader screen that will appear till you finish with api parsing. And for api parsing you can try something like queue, so until all request finishes the loader screen will show.

I hope it will give you some idea.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top