[英]NSURLConnection sendAsynchronousRequest:queue:completionHandler not working in iOS 4.3
[英]NSURLConnection sendAsynchronousRequest:queue:completionHandler: making multiple requests in a row?
我一直在使用NSURLConnection's
sendAsynchronousRequest:queue:completionHandler:
方法很棒。 但是,我现在需要连续发出多个请求。
如何在使用这种伟大的异步方法的同时做到这一点?
根据您想要的行为,您可以通过多种方式执行此操作。
您可以一次发送一堆异步请求,跟踪已完成的请求数,并在完成所有操作后执行一些操作:
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如果你使用其中任何一个,你应该添加一些错误检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.