繁体   English   中英

发出过多 AFNetworking 请求时超时

[英]Timeout when issuing too many AFNetworking requests

我有这个代码来下载 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 中不会发生。

有什么问题?

如果您指定操作队列的maxConcurrentOperationCount ,它将控制尝试并发操作的数量,从而减轻由于 iOS 限制允许的同时网络连接数量而导致的任何超时:

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM