I have n tasks sending to a server. When I launch them by [taskN resume]
they will launch parallelly but i want to launch them sequentially - if first task finish, other task will launch.
Any suggestions?
I came with quite simple solution without subclassing:
Sample:
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue setMaxConcurrentOperationCount:1];
// first download task
[queue addOperationWithBlock:^{
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); // create a semaphore
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionTask *task1 = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
dispatch_semaphore_signal(semaphore); // go to another task
}];
[task1 resume];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); // wait to finish downloading
}];
// second download task
[queue addOperationWithBlock:^{
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionTask *task2 = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
dispatch_semaphore_signal(semaphore);
}];
[task2 resume];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
}];
These two operations (task1, task2) will execute sequentially, so they will wait until n-1 operation will finish.
Using semaphores inspired in NSURLSession with NSBlockOperation and queues
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With