Ios 发出太多网络请求时超时
我有这个代码来下载40个jsonIos 发出太多网络请求时超时,ios,objective-c,json,afnetworking-2,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 *re
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。
它只在边缘模式下发生,在wifi和3g中不会发生
问题是什么?如果指定操作队列的
maxConcurrentOperationCount
,将控制尝试的并发操作数量,从而减少因iOS限制允许的同时网络连接数量而导致的超时:
manager.operationQueue.maxConcurrentOperationCount = 4;
[manager.operationQueue addOperations:operations waitUntilFinished:NO];
如果没有这一点,当您提交40个操作时,所有操作都可能尝试启动NSURLConnection
对象,即使一次只能运行4或5个。在连接速度较慢的情况下,这可能会导致后面的一些请求超时
如果指定
maxConcurrentOperationCount
,则在之前的连接完成之前,它不会尝试启动后一个连接。您仍然可以享受并发请求的性能优势,但不会因为iOS强制执行的并发NSURLConnection
请求的限制而导致大量请求超时。听起来连接太慢,服务器抛出超时错误。