NSURLConnection sendAsynchronous多个请求未执行

时间:2015-01-14 06:29:46

标签: ios asynchronous queue httprequest nsurlconnection

我向网络服务发送了10个url请求(在for循环中)

并期望获得10个JSON格式数据作为单独返回

这是我的代码:

NSArray *reqArray = [10 requests of url inside];
NSMutableArray * saveArray = [prepare to store 10 JSON data in here];
NSInteger counter = [reqArray count];

for (NSURLRequest *request in reqArray) {
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                               NSDictionary *result1 = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                               NSDictionary *result2 = [result1 objectForKey:@"keyForValueIWant"];
                               [saveArray addObject:result2];
                            counter -- ;
                               if (counter == 0) {
                                   NSLog(@"all done");

                               }
                           }];

}

completionHandler永远不会被执行,我总是得不到任何回报。

有什么我误解了NSURLConnetion或我做错了吗?

任何建议都将不胜感激!

修改

我发现代码在viewDidLoad(我放的地方)中的所有其他代码完成后执行

即使我尝试将其包装在 dispatch_async(dispatch_get_main_queue(),^ {}

每当我打电话时,它能立即起作用吗? sendSynchronous请求?

1 个答案:

答案 0 :(得分:0)

我猜你是从主循环开始那些连接,试试:

NSArray *reqArray = [10 requests of url inside];
NSMutableArray * saveArray = [prepare to store 10 JSON data in here];
NSInteger counter = [reqArray count];

for (NSURLRequest *request in reqArray) {
    dispatch_async(dispatch_get_main_queue(), ^{ 
        [NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)     {
                           NSDictionary *result1 = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                           NSDictionary *result2 = [result1 objectForKey:@"keyForValueIWant"];
                           [saveArray addObject:result2];
                        counter -- ;
                           if (counter == 0) {
                               NSLog(@"all done");

                           }
                       }];
    });
}

因为NSURLConnection需要执行runloop,所以如果runloop结束,则连接结束。