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

标签 ios objective-c nsurlconnection sendasynchronousrequest

我正在尝试以编程方式创建一个 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
    }
}

今天,我尝试了 NSURLConnectionsendAsync 来使用循环一个接一个地触发所有连接,并且效果很好。

   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 的最佳方案是什么>NSURLConnection 与 asyncReq?

最佳答案

一些观察:

  1. 使用 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 discussion)。只有在连接速度较慢时才会出现问题(超时、UI 问题等)。

  4. 我建议使用分派(dispatch)组或操作队列依赖项,而不是递减挂起请求数的计数器。

    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. 顺便说一句,如果您使用基于委托(delegate)的连接,就像您在原始问题中所做的那样,您应该didReceiveData 中解析数据。那应该只是将数据附加到 NSMutableData。在 connectionDidFinishLoading 委托(delegate)方法中执行所有解析。

    如果您转到基于 block 的实现,这个问题就会消失,但只是对您的代码片段的观察。

关于ios - 处理多个 NSURL 连接的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31343589/

相关文章:

ios - Xcode 9.4 fatal error : lipo: can't open input file (No such file or directory)

objective-c - 标签栏 Controller 项目从右侧开始

ios - iOS NSURLConnection字典或数组

ios - 具有不同可选部分的 UITableView?

iphone - iOS 在另一个项目中使用现有项目的类/资源文件

iphone - Obj-C,带有 ARC 代码和警告的库 - 方法可能缺少 [super dealloc] 调用?

ios - 如何有效地解析 mpeg 文件?

objective-c - UICollectionView 不重新加载单元格的 imageView

iphone - 如何在下载之前获取文档大小

ios - 上传图像时对象引用未设置为 object.postmethod POST 文件名文件的实例,但**与 Android 代码一起正常工作**