2014-03-24 52 views
2

我有这样的代码来下载40 JSON超时发出过多AFNetworking当请求

NSMutableArray *mutableOperations = [NSMutableArray array]; 
    for (NSDictionary *dict in general_URL) { 

     NSURL *url = [dict objectForKey:@"url"]; 
     NSString *key = [dict objectForKey:@"key"]; 

     NSURLRequest *request = [NSURLRequest requestWithURL:url]; 

     AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 
     operation.responseSerializer = [AFHTTPResponseSerializer serializer]; 
     [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 

      [self.all_data setObject:[self parseJSONfile:responseObject] forKey:key]; 

     } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
      NSLog(@"Error: %@", error); 
     }]; 

     [mutableOperations addObject:operation]; 
    } 

    NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:mutableOperations progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) { 
     NSLog(@"progress:%f", (float)numberOfFinishedOperations/totalNumberOfOperations); 
    } completionBlock:^(NSArray *operations) { 

     NSLog (@"all done"); 

    }]; 
    [manager.operationQueue addOperations:operations waitUntilFinished:NO]; 

正如你可以看到我用一个经理有请求的队列。问题是,突然间,它以-1001代码超时。 它只发生在EDGE模式下,在wifi和3G中不会发生。

有什么问题?

+0

声音像连接太慢,服务器会引发超时错误。 – Tander

回答

2

如果指定的操作队列的maxConcurrentOperationCount,将控制并发操作有多少尝试,从而缓解的事实而造成的任何超时是iOS的限制多少同步网络连接被允许:

manager.operationQueue.maxConcurrentOperationCount = 4; 
[manager.operationQueue addOperations:operations waitUntilFinished:NO]; 

在没有这个的情况下,当你提交你的40个操作时,所有这些操作都可能试图启动NSURLConnection个对象,即使每次只能运行4个或5个对象。在慢速连接时,这可能会导致您的某些后续请求超时。

如果指定maxConcurrentOperationCount,它将不会尝试启动后面的连接,直到先前的连接完成。您仍然可以享受并发请求带来的性能优势,但是您不会因为限制iOS执行的并发NSURLConnection请求而导致一堆请求超时。

+1

是啊!!!!!!!!!!!! – CrazyDev