gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 05:20:16 26 4
gpt4 key购买 nike

我想按顺序下载 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com