objective-c - AFNetworking 并发 Http 请求

标签 objective-c performance cocoa connection httprequest

我需要从 API 下载大约 200 个文件。它们都只有 15KB 左右。 我当前的代码如下所示:

NSOperationQueue* opQueue = [[NSOperationQueue alloc]init];
[opQueue setMaxConcurrentOperationCount:8];

NSString* baseUrl = @"https://someapi.com/somejson.json?page=";

for(int n = 0; n <= numberOfPages; n++) {
    @autoreleasepool {

         NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%d", baseUrl, n]]cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20];


        AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
        operation.responseSerializer = [AFJSONResponseSerializer serializer];

        [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"Done");
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"Error");
        }];

        [opQueue addOperation:operation];

    }
};

虽然这工作正常,但我很好奇是否有更快的方法来做到这一点。目前下载文件大约需要 20 秒。由于它们都那么小,我猜花费最多时间的是等待服务器响应。是否有更好的方法对它们进行排队,以便所有连接都在“同一”时间建立,或者这只是一种硬上限?

我已经尝试过设置

[opQueue setMaxConcurrentOperationCount:8];

各种不同的值,以及根本不设置它。但这似乎并没有真正提高性能。

这是其中一个连接的 Charles 日志。其他的几乎相同,但如果有必要我可以发布更多内容。

URL https://<hidden>&page=0
Status  Complete
Response Code   200 OK
Protocol    HTTP/1.1
Method  GET
Kept Alive  No
Content-Type    application/json; charset=utf-8
Client Address  /127.0.0.1
Remote Address  <hidden>
Timing  
Request Start Time  24.02.15 09:49:58
Request End Time    24.02.15 09:49:58
Response Start Time 24.02.15 09:49:59
Response End Time   24.02.15 09:49:59
Duration    1.18 sec
DNS 1 ms
Connect 42 ms
SSL Handshake   127 ms
Request 0 ms
Response    1 ms
Latency 974 ms
Speed   8,36 KB/s
Response Speed  9.626,95 KB/s

Size    
Request Header  283 bytes
Response Header 552 bytes
Request -
Response    9,09 KB (9306 bytes)
Total   9,90 KB (10141 bytes)
Request Compression -
Response Compression    91,8% (gzip) 

最佳答案

看起来延迟是获得请求响应所需时间的主要因素。可能的原因之一是使用代理网络。另请注意,不仅仅是延迟,连接、SSL 握手所需的时间也会导致持续时间 1.18 秒

关于objective-c - AFNetworking 并发 Http 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28633277/

相关文章:

ios - CoreData 不跨多个 iOS 设备存储数据

ios - iOS 9 中的自定义字体问题?

iOS : Internet connection is available but getting time out error in web service call , 相同的网络服务在 android 中运行

java - 使用 YourKit 分析应用程序,仍然无法识别 CPU 占用

c# - clr 的原因! PerfView CPU 堆栈中的 JIT_New

macos - 在运行时更新默认打印机名称

macOS 商店沙箱应用程序使用 NSOpenPanel 选择下载文件夹,但无法再次访问该文件夹

iPhone/Objective-C - 在字符串中搜索特定单词

python - 如何使大型 python 数据结构更有效地解开?

macos - NSTableView 中的悬停效果问题