NSURLConnection sendAsynchronousRequest:queue:completionHandler:在一行中发出多个请求?

我一直在使用NSURLConnection's sendAsynchronousRequest:queue:completionHandler:方法非常棒。 但是,我现在需要连续发出多个请求。

我仍然在使用这个很好的asynchronous方法的时候怎么能这样做呢?

有很多方法可以根据你想要的行为来做到这一点。

您可以一次发送一堆asynchronous请求,跟踪已完成请求的数量,并在完成所有请求后执行一些操作:

 NSInteger outstandingRequests = [requestsArray count]; for (NSURLRequest *request in requestsArray) { [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { [self doSomethingWithData:data]; outstandingRequests--; if (outstandingRequests == 0) { [self doSomethingElse]; } }]; } 

你可以把块连在一起:

 NSMutableArray *dataArray = [NSMutableArray array]; __block (^handler)(NSURLResponse *response, NSData *data, NSError *error); NSInteger currentRequestIndex = 0; handler = ^{ [dataArray addObject:data]; currentRequestIndex++; if (currentRequestIndex < [requestsArray count]) { [NSURLConnection sendAsynchronousRequest:[requestsArray objectAtIndex:currentRequestIndex] queue:[NSOperationQueue mainQueue] completionHandler:handler]; } else { [self doSomethingElse]; } }; [NSURLConnection sendAsynchronousRequest:[requestsArray objectAtIndex:0] queue:[NSOperationQueue mainQueue] completionHandler:handler]; 

或者你可以在一个ansynchronous块中同步执行所有的请求:

 dispatch_queue_t callerQueue = dispatch_get_current_queue(); dispatch_queue_t downloadQueue = dispatch_queue_create("Lots of requests", NULL); dispatch_async(downloadQueue, ^{ for (NSRURLRequest *request in requestsArray) { [dataArray addObject:[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]]; } dispatch_async(callerQueue, ^{ [self doSomethingWithDataArray:dataArray]; }); }); }); 

PS如果你使用任何这些你应该添加一些错误检查。