发出过多AFNetworking请求时超时

时间:2014-03-24 18:06:19

标签: ios objective-c json afnetworking-2

我有这个代码可以下载40 json

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中它不会发生。

问题是什么?

1 个答案:

答案 0 :(得分:2)

如果指定操作队列的maxConcurrentOperationCount,那将控制尝试的并发操作数,从而减少因iOS限制允许的并发网络连接数而导致的任何超时:

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

如果没有这个,当你提交40个操作时,所有这些操作都可能会尝试启动NSURLConnection个对象,即使一次只能运行4个或5个。在慢速连接上,这可能导致后面的一些请求超时。

如果指定maxConcurrentOperationCount,则在先前的连接完成之前,它不会尝试启动后一个连接。您仍然可以享受并发请求的性能优势,但是由于iOS强制执行并发NSURLConnection请求的限制,您不会发出一堆超时的请求。

相关问题