6

プログラムでxlsシートを作成しようとしています。シートを埋めるために、倍数NSURLConnectionを約100にしています。現在、私のアプローチは次のとおりです。

  1. 接続を確立し、データを配列に格納します。この配列には 100 個のオブジェクトがあります。
  2. 次に、最初のオブジェクトを取得して、接続を呼び出します。データを保存します。そして、配列内の 2 番目のオブジェクトとの 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];
    }
 }

}

1 つの接続が終了した後に別の接続を呼び出す:

// 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た。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ですかNSURLConnection with asyncReq?

4

2 に答える 2

1

を使用するsendAsynchronousことは、コード構成を改善する優れた方法です。慎重に精査すれば、マージンで速度を向上させることができると確信していますが、速度を著しく向上させる方法は、100 の要求を行わないことです。

レスポンス ボディが小さい場合は、結果の結合に応答するエンドポイントを作成します。

応答本文が大きい場合は、ユーザーが現時点で必要とするよりも多くのデータを要求しています。ユーザーが見る必要があるものだけを UI に保持し、残りは黙って取得します (... または、黙っているよりは怠惰に)。

サーバーを制御せず、応答本文が小さく、ユーザーがアプリを続行するためにすべてまたはほとんどを必要とする場合は、マージンでのパフォーマンスと、アプリの使用中にユーザーを楽しませるための UI トリックに取り組み始めることができます。機能しますが、通常、これらの制約の 1 つ (通常は後者) は緩和できます。

于 2015-07-10T15:04:11.900 に答える