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

在类中创建两个变量来存储当前下载的数据长度和预期的数据长度(你可以做得更优雅)

int downloadedLength;
int expectedLength;

要知道预期数据的长度,您必须从 didReceiveResponse 委托中获取

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

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

要更新下载的长度,您必须在 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 回答