ios - 在 iOS 中使用 NSURLConnection 按顺序下载文件

标签 ios objective-c ios7 ios8 grand-central-dispatch

我想按顺序下载 3 个文件。其中两个是 txt 文件,一个是 .gz 文件。我正在使用 NSURLConnection 下载上述文件。

我是 iOS 编程的新手。我在 SO 和 google 的其他问题中看到我们可以使用串行调度队列串行地执行一些操作。

但我不知道如何使用 NSURLConnection 来做到这一点。我在下面尝试过但没有成功。

 dispatch_queue_t serialQueue = dispatch_queue_create("com.clc.PropQueue", DISPATCH_QUEUE_SERIAL);
dispatch_async(serialQueue, ^{
    [self downloadProp];
});
dispatch_async(serialQueue, ^{
    [self downloadDatabase];
});
dispatch_async(serialQueue, ^{
    [self downloadTxt];
});

上面的代码没有执行 NSURLCOnnection 的 connectionDidFinishLoading。任何人都知道如何实现这一点?

最佳答案

NSURLSession 提供了一个队列,它将按照创建任务的顺序下载每个任务。

<罢工>

<罢工>
NSURLSession *session = [NSURLSession sharedSession];

NSURLSessionTask *task1 = [session dataTaskWithURL:[NSURL URLWithString:@"http://yahoo.com"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    NSLog(@"Complete 1");
}];
NSURLSessionTask *task2 = [session dataTaskWithURL:[NSURL URLWithString:@"http://msn.com"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    NSLog(@"Complete 2");
}];
NSURLSessionTask *task3 = [session dataTaskWithURL:[NSURL URLWithString:@"http://google.com"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    NSLog(@"Complete 3");
}];

// Regardless of which order the tasks are "resumed" (aka started) they will execute synchronously in the order added, above.
[task3 resume];
[task1 resume];
[task2 resume];

<罢工>

根据评论和聊天更新:

为了更加确定任务的排序和执行...

NSURLSession *session = [NSURLSession sharedSession];

__block NSURLSessionTask *task1 = nil;
__block NSURLSessionTask *task2 = nil;
__block NSURLSessionTask *task3 = nil;

task1 = [session dataTaskWithURL:urlToFirstFile completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    // CHECK ERROR
    NSLog(@"First file completed downloading");
    [task2 resume];
}];
task2 = [session dataTaskWithURL:urlToSecondFile completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    // CHECK ERROR
    NSLog(@"Second file completed downloading");
    [task3 resume];
}];
task3 = [session dataTaskWithURL:[NSURL URLWithString:@"http://google.com"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    // CHECK ERROR
    NSLog(@"Third file completed downloading");
}];

[task1 resume];

关于ios - 在 iOS 中使用 NSURLConnection 按顺序下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31385368/

相关文章:

ios - 如何在 objective-c 中的MDDatePicker中设置最大日期

objective-c - 当使用 NSOperation 在 iOS 7 中使用 Background Fetch 调用 completionHandler

ios - 如何从 ipad 内置视频应用访问视频

objective-c - 在 IB 中轮换标签?

objective-c - 如何使用 Cocoa 和 CGDisplayCreateImageForRect 在 Mac OS X 中截取区域屏幕截图?

swift - 在 Testflight beta 测试中进行测试时应用程序崩溃了

ios - 以编程方式创建具有多个标签的 UIView

objective-c - 带音频的计时器精度

ios - 隐藏导航栏和标签栏后 UICollectionView 框架发生变化

ios - remoteIO音频单元播放回调中的AudioBufferList内容