【问题标题】:Timeout when issuing too many AFNetworking requests发出太多 AFNetworking 请求时超时
【发布时间】:2014-03-24 18:06:18
【问题描述】:

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

有什么问题?

【问题讨论】:

  • 好像连接太慢,服务器抛出超时错误。

标签: ios objective-c json afnetworking-2


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-26
    • 2012-07-02
    • 1970-01-01
    • 2014-03-22
    • 1970-01-01
    相关资源
    最近更新 更多