1

NSURLConnectionクラスのsendSynchronousRequest:returningResponse:errorメソッドを使用して、ネットワークからNSDataを取得します。

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html

NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

私がやりたいのは、戻り値が有効かどうかを確認することです。そこで、以下のように、データの長さと応答ヘッダーの予想される長さを比較しました。

NSData *urlData;
do {
    urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    if ([urlData length] != [response expectedContentLength]) {
        NSLog(@"WTF!!!!!!!!! NSURLConnection response[%@] length[%lld] [%d]", [[response URL] absoluteString], [response expectedContentLength], [urlData length]);
        NSHTTPURLResponse *httpresponse = (NSHTTPURLResponse *) response;
        NSDictionary *dic = [httpresponse allHeaderFields];
        NSLog(@"[%@]", [dic description]);
    }
} while ([urlData length] != [response expectedContentLength]);

ただし、返されたデータの整合性を確保するのに十分かどうかはわかりません。リモートサーバー上のファイルのチェックサムを確認できません。

あなたの経験や他のヒントを共有できますか?

ありがとう。

4

1 に答える 1

2

クラスに2つの変数を作成して、現在ダウンロードされているデータの長さと予想されるデータの長さを格納します(より洗練された方法で実行できます)

int downloadedLength;
int expectedLength;

予想されるデータの長さを知るには、didReceiveResponseデリゲートからデータを取得する必要があります

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{

//    NSLog(@"expected: %lld",response.expectedContentLength);
    expectedLength = response.expectedContentLength;
    downloadedLength = 0;
}

downloadedLenghtを更新するには、didReceiveDataでそれを増やす必要があります。

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
downloadedLength = downloadedLength + [data length];
//...some code
}

次に、ダウンロードしたデータがconnectionDidFinishLoadingの要件に適合するかどうかを比較するために、任意のロジックを実行できます。

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

    if (downloadedLength == expectedLength) {
        NSLog(@"correctly downloaded");
    }
    else{
        NSLog(@"sizes don't match");
        return;
    }
}

(HJMOHandlerで)不完全にダウンロードされた大きな画像に関するHJCacheライブラリの問題を修正するためにこれを行う必要がありました。

于 2012-03-18T17:01:26.700 に答える