How to make a queue of NSURLRequest using GCD?

2019-08-02 19:13发布

问题:

I have a NSMutableArray containing 7 internet URLs from which I need to grab the HTTP headers.

I'm using these methods to make asynchronous connections (and all works perfectly):

- (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

The problem is that I need to download each URL following the order of the NSMutableArray, but due to the nature of the asynchronous connection the order gets messed up.

I don't want to use synchronous connections because they block the Main Thread.

How do I make a queue using GCD on the Main Thread to ensure that the downloads will follow the order of indexes from 0 to 6 of my NSMutableArray containing the 7 URLs?

Thanks for your help!

回答1:

You do not need GCD for that. You can start with the first download, and in connectionDidFinishLoading or didFailWithError start the next download. You would only need to maintain an index of the current download, so that you know if you are finished or which download to start next.

The following is just a sketch of this idea:

// 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.
}


回答2:

I think the other solution is rather inflexible and it might be nicer to do this using NSOperation. A nice introduction to it can be found on NSHipster and Apple's documentation. There're also several Stack Overflow questions about this topic and this.