处理多个 NSURL 连接的最佳方式

2023-11-24

我正在尝试以编程方式创建 xls 工作表。为了填写表格,我正在制作倍数NSURLConnection大约100。现在,我的方法是:

  1. 建立连接并将数据存储到数组中。该数组有 100 个对象。
  2. 现在获取第一个对象并调用连接。存储数据。并与数组中的第二个对象建立第二个连接。这一直持续到数组中的最后一个对象。

完成 100 个连接平均需要 14 秒。有没有什么办法可以实现NSURLConnection以更快的方式获得响应?

直到昨天我遵循的基本方法如下:

声明属性:

@property (nonatomic,strong) NSURLConnection *getReportConnection;
@property (retain, nonatomic) NSMutableData *receivedData;
@property (nonatomic,strong) NSMutableArray *reportArray;

初始化数组在viewDidLoad:

reportArray=[[NSMutableArray alloc]init];

初始化NSURLConnection在按钮操作中:

/initialize url that is going to be fetched.
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"****/%@/crash_reasons",ID]];

//initialize a request from url
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request addValue:tokenReceived forHTTPHeaderField:@"**Token"];

[request setHTTPMethod:@"GET"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

//initialize a connection from request
self.getReportConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

处理接收到的数据:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data{
if (connection==_getVersionConnection) {

    [self.receivedData_ver appendData:data];

    NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    NSError *e = nil;
    NSData *jsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding];

    NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:jsonData options: NSJSONReadingMutableContainers error: &e];
    [JSON[@"app_versions"] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if (![obj[@"id"] isEqual:[NSNull null]] && ![reportArray_ver containsObject:obj[@"id"]]) {

            [reportArray_ver addObject:obj[@"id"]];

        }
        NSLog(@"index = %lu, Object For title Key = %@", (unsigned long)idx, obj[@"id"]);
    }];

    if (JSON!=nil) {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Version Reports succesfully retrieved" message:@"" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
        [alert show];
    }
 }

}

一个连接完成后调用另一个连接:

// This method is used to process the data after connection has made successfully.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
   if (connection==getReportConnection) {

             //check and call the connection again
    }
}

今天,我尝试了NSURLConnection with sendAsync使用循环一个接一个地触发所有连接,效果非常好。

   self.receivedData_ver=[[NSMutableData alloc]init];
__block NSInteger outstandingRequests = [reqArray count];
 for (NSString *URL in reqArray) {

    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:URL]
                                                         cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                     timeoutInterval:10.0];

    [request setHTTPMethod:@"GET"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];


[NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response,
                                           NSData *data,
                                           NSError *connectionError) {

                           [self.receivedData appendData:data]; //What is the use of appending NSdata into Nsmutable data? 

                           NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

                           NSError *e = nil;
                           NSData *jsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding];

                           NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:jsonData options: NSJSONReadingMutableContainers error: &e];
                           NSLog(@"login json is %@",JSON);

                           [JSON[@"app_versions"] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {


                               if (![obj[@"id"] isEqual:[NSNull null]] && ![reportArray_ver containsObject:obj[@"id"]]) {

                                   [reportArray_ver addObject:obj[@"id"]];

                               }

                               NSLog(@"index = %lu, Object For title Key = %@", (unsigned long)idx, obj[@"id"]);
                           }];


                          outstandingRequests--;

                           if (outstandingRequests == 0) {
                               //all req are finished
                               UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Version Reports succesfully retrieved" message:@"" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
                               [alert show];
                           }

                       }];
}

这次完成 100 个请求的时间比旧程序减少了一半,除了 asynReq 之外还有其他更快的方法吗?最好的使用场景是什么NSURLconnection and NSURLConnection with asyncReq?


一些观察结果:

  1. Use NSURLSession而不是NSURLConnection(如果您支持 iOS 7.0 及更高版本):

    for (NSString *URL in URLArray) {
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
    
        // configure the request here
    
        // now issue the request
    
        NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            // check error and/or handle response here
        }];
        [task resume];
    }
    
  2. 如果您绝对必须发出 100 个请求,请像您的系统一样同时发出它们sendAsynchronousRequest实施(或我的dataTaskWithRequest),不是按顺序。这就是实现巨大性能优势的原因。

    但请注意,您无法保证它们完全按照您发布的顺序排列,因此您将需要使用一些支持该结构的结构(例如使用NSMutableDictionary或预先填充NSMutableArray使用占位符,这样您就可以简单地更新特定索引处的条目,而不是将项目添加到数组中)。

    最重要的是,请注意它们可能不会按照要求的顺序完成,因此请确保正确处理。

  3. 如果您保留 100 个单独的请求,我建议您在非常慢的网络连接上进行测试(例如,使用网络链接调节器来模拟非常糟糕的网络连接;请参阅NSHipster 讨论)。只有在连接速度较慢时执行此操作时才会出现一些问题(超时、UI 打嗝等)。

  4. 我建议使用调度组或操作队列依赖项,而不是减少待处理请求数量的计数器。

    dispatch_group_t group = dispatch_group_create();
    
    for (NSString *URL in URLArray) {
        dispatch_group_enter(group);
    
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
    
        // configure the request here
    
        // now issue the request
    
        NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            // check error and/or handle response here
    
            // when all done, leave group
    
            dispatch_group_leave(group);
        }];
        [task resume];
    }
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        // do whatever you want when all of the requests are done
    });
    
  5. 如果可能,请查看是否可以重构 Web 服务,以便发出一个返回所有数据的请求。如果您正在寻求进一步的性能改进,这可能就是实现这一目标的方法(并且它避免了发出 100 个单独请​​求时涉及的许多复杂性)。

  6. 顺便说一句,如果您使用基于委托的连接,就像您在原始问题中所做的那样,您应该not正在解析数据didReceiveData。那应该只是将数据附加到NSMutableData。进行所有解析connectionDidFinishLoading委托方法。

    如果您采用基于块的实现,这个问题就会消失,但只需对代码片段进行观察即可。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

处理多个 NSURL 连接的最佳方式 的相关文章

随机推荐