![](/img/trans.png)
[英]AFNetworking requests got timeout too early in very bad network condition
[英]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.