Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Several DownloadTasks sequentially

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?

like image 913
Patrik Vaberer Avatar asked Jan 10 '23 07:01

Patrik Vaberer


1 Answers

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

like image 184
Patrik Vaberer Avatar answered Jan 21 '23 10:01

Patrik Vaberer