ios - 几个DownloadTasks顺序

标签 ios nsurlsessiondownloadtask

我有 n 个任务发送到服务器。当我通过 [taskN resume] 启动它们时,它们将并行启动,但我想按顺序启动它们 - 如果第一个任务完成,其他任务将启动。 有什么建议吗?

最佳答案

我提出了一个非常简单的解决方案,没有子类化:

示例:

    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);

    }];

这两个操作(任务 1、任务 2)将按顺序执行,因此它们将等待直到 n-1 个操作完成。

使用受 NSURLSession with NSBlockOperation and queues 启发的信号量

关于ios - 几个DownloadTasks顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24526342/

相关文章:

iphone - 检测一个int是否连续重复

ios - 使用 NSURLSessionDownloadTask 在 UITableView 中下载图像的堆分配激增

ios - 如何在ios中恢复大文件的下载

ios - 从 Objective-C 中的数组获取唯一对象集的最佳方法是什么

iphone - loadView 与 init 方法

ios - 多个文件下载有问题

ios - NSURLSession backgroundSession 完成时额外的 API 调用

ios - Swift:URLSessionDownload 文件说它存在但实际上不存在?

ios - UITableViewCell 内标签的 NSLayoutConstraint

ios - 搜索字典数组的简便方法