繁体   English   中英

如何使用GCD使NSURLRequest排队?

[英]How to make a queue of NSURLRequest using GCD?

我有一个包含7个Internet URLsNSMutableArray ,我需要从中获取HTTP标头。

我正在使用以下方法进行asynchronous连接(所有方法均正常运行):

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
- (void)connectionDidFinishLoading:(NSURLConnection *)connection

问题是我需要按照NSMutableArray的顺序下载每个URL ,但是由于asynchronous连接的性质,该顺序变得混乱了。

我不想使用synchronous连接,因为它们会阻塞Main Thread.

如何在Main Thread上使用GCD进行排队,以确保下载遵循我的NSMutableArray包含7个URLs的索引从0到6的顺序?

谢谢你的帮助!

您不需要GCD。 您可以从第一次下载开始,然后在connectionDidFinishLoadingdidFailWithError开始下一次下载。 您只需要维护当前下载的索引,这样就可以知道您是否已完成下载或下一步要开始下载。

以下只是这个想法的草图:

// Start the first download:
self.currentDownload = 0;
request = [NSURLRequest requestWithURL:[self.myURLArray objectAtIndex:0]];
connection = [NSURLConnection connectionWithRequest:request delegate:self];

// and in connectionDidFinishLoading/didFailWithError:
self.currentDownload++;
if (self.currentDownload < self.myURLArray.count) {
    request = [NSURLRequest requestWithURL:[self.myURLArray objectAtIndex:self.currentDownload]];
    connection = [NSURLConnection connectionWithRequest:request delegate:self];
} else {
     // All downloads finished.
}

我认为另一种解决方案不太灵活,使用NSOperation进行此操作可能会更好。 可以在NSHipsterApple的文档中找到对它的很好介绍。 关于此主题和this,还有几个Stack Overflow问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM