2014-03-24 53 views
2

我有這樣的代碼來下載40 JSON超時發出過多AFNetworking當請求

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中不會發生。

有什麼問題?

+0

聲音像連接太慢,服務器會引發超時錯誤。 – Tander

回答

2

如果指定的操作隊列的maxConcurrentOperationCount,將控制併發操作有多少嘗試,從而緩解的事實而造成的任何超時是iOS的限制多少同步網絡連接被允許:

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

在沒有這個的情況下,當你提交你的40個操作時,所有這些操作都可能試圖啓動NSURLConnection個對象,即使每次只能運行4個或5個對象。在慢速連接時,這可能會導致您的某些後續請求超時。

如果指定maxConcurrentOperationCount,它將不會嘗試啓動後面的連接,直到先前的連接完成。您仍然可以享受併發請求帶來的性能優勢,但是您不會因爲限制iOS執行的併發NSURLConnection請求而導致一堆請求超時。

+1

是啊!!!!!!!!!!!! – CrazyDev