NSURLSession任务执行顺序

tut*_*u47 2 iphone ios nsurlsession nsurlsessionuploadtask

我将多个任务按顺序添加到NSURLSession(后台模式)中。我保持HTTPMaximumConnectionsPerHost =1。但是,我看到上传是按照随机顺序进行的,即,在第一个项目可能是第5个项目被拾取之后,第3个项目等等,等等-上载没有按顺序进行我提供给NSURLSession。有没有一种方法可以完全按照上传的顺序订购上传内容?

HSG*_*HSG 5

我们不保证您的执行任务将按配置顺序执行,HTTPMaximumConnectionsPerHost = 1因为它仅保证一次执行一个任务。就顺序同步执行任务而言,可以使用NSOperationQueue和NSOperation在操作之间添加依赖项。

NSMutableArray *operations = [NSMutableArray array];
    NSArray *urls = @[];
    NSURLSession *urlSession = [NSURLSession sharedSession];
    for (int i = 0;i < urls.count;i++) {
        NSOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
            NSURLSessionDataTask *task = [urlSession dataTaskWithURL:[NSURL URLWithString:urls[i]] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            }];
            [task resume];
        }];
        i > 0 ? [operation addDependency:operations[i - 1]] : 0;
        [operations addObject:operation];
    }
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    queue.maxConcurrentOperationCount = 1;
    [queue addOperations:operations waitUntilFinished:YES];
Run Code Online (Sandbox Code Playgroud)

另一个解决方案是GCD的使用调度信号量。

dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    NSArray *urls = @[];
    NSURLSession *urlSession = [NSURLSession sharedSession];
    for (NSString *url in urls) {
        NSURLSessionDataTask *task = [urlSession dataTaskWithURL:[NSURL URLWithString:url] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            dispatch_semaphore_signal(semaphore);                  // signal when done
        }];
        [task resume];
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); // wait for signal before continuing
    }
    //Do s.t after all tasks finished
Run Code Online (Sandbox Code Playgroud)