3

我正在按顺序向 NSURLSession (background mode) 添加多个任务。我一直保持 HTTPMaximumConnectionsPerHost = 1。但是,我看到上传是按随机顺序进行的,即在第 1 项可能是第 5 项被拾取之后,然后是第 3 项等 - 上传不会按顺序发生我已经提供给 NSURLSession。有没有办法完全按照添加的方式订购上传?

4

1 回答 1

6

我们不确保您的执行任务将按照配置的顺序执行,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];

另一种解决方案是使用 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
于 2015-10-19T16:36:03.210 回答