首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >NSURLConnection sendAsynchronousRequest:queue:completionHandler:在一行中发出多个请求?

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

Stack Overflow用户
提问于 2012-02-23 16:07:40
回答 1查看 53.9K关注 0票数 54

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

我如何在使用这个伟大的异步方法的同时做到这一点呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-02-23 16:53:20

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

您可以一次发送一组异步请求,跟踪已完成的请求的数量,并在它们全部完成后执行某些操作:

代码语言:javascript
复制
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];
        }
    }];
}

您可以将这些块链接在一起:

代码语言:javascript
复制
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];

或者,您可以在一个异步块中同步完成所有请求:

代码语言:javascript
复制
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];
        });
    });
});

附注:如果你使用其中的任何一个,你应该添加一些错误检查。

票数 109
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9409211

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档