OGeek|极客世界-中国程序员成长平台

标题: ios - 发出太多 AFNetworking 请求时超时 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 08:53
标题: ios - 发出太多 AFNetworking 请求时超时

我有这个代码可以下载 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 addObjectperation];
    }

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

        NSLog (@"all done");

    }];
    [manager.operationQueue addOperationsperations waitUntilFinished:NO];

如您所见,我使用管理器来处理请求队列。问题是突然间,它以 -1001 代码超时。 它仅在 EDGE 模式下发生,在 wifi 和 3g 下不会发生。

有什么问题?



Best Answer-推荐答案


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

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

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

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

关于ios - 发出太多 AFNetworking 请求时超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22617233/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4