【问题标题】:NSURLSession task execution orderNSURLSession 任务执行顺序
【发布时间】:2015-10-19 13:46:32
【问题描述】:

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

【问题讨论】:

  • 你应该在完成最后一项后调用下一项请显示你的代码
  • 我尝试链接上传。但是当第一个项目完成并在后台安排第二次上传时,它开始上传然后突然停止。第二项不会在后台上传。

标签: ios iphone nsurlsession nsurlsessionuploadtask


【解决方案1】:

我们不保证你的执行任务会按照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

【讨论】:

  • 我尝试使用 NSOperationQueue,但在后台上传模式下它变得非常混乱。正如这里提到的:stackoverflow.com/questions/21918722/…,我认为它并不简单实用。我也尝试过链接上传,但它突然停止与第二项(大约 30 秒后,操作系统在后台唤醒时暂停您的应用程序)。
  • @tuttu47 能否请您在这里发布您的代码,以便我们轻松找出问题。
  • 我在这里添加了详细的代码描述:stackoverflow.com/questions/33285179/…
猜你喜欢
  • 2019-12-06
  • 1970-01-01
  • 1970-01-01
  • 2021-12-16
  • 1970-01-01
  • 2021-09-01
  • 2017-05-13
  • 1970-01-01
  • 2018-12-25
相关资源
最近更新 更多