4

我需要从 URL 检查文件的大小。使用 AFNetworking 下载文件时,我得到了完美的文件大小。

AFHTTPRequestOperation *operation = [client HTTPRequestOperationWithRequest:request
                                                                        success:^(AFHTTPRequestOperation *operation, id responseObject) {
                                                                            // Success Callback

                                                                        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                                                            // Failure Callback

                                                                        }];

并在另一个块中获取文件大小

[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {

    }];

但是我需要在启动下载请求之前检查文件大小,以便我可以提示用户。我也试过另一种方法

NSURL *url = [NSURL URLWithString:@"http://lasp.colorado.edu/home/wp-content/uploads/2011/03/suncombo1.jpg"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSLog(@"original = %d", [data length]);

但它会阻止 UI,因为它会下载所有数据来计算其大小。有没有办法在下载前检查文件大小?任何帮助表示赞赏。

4

2 回答 2

21

如果服务器支持它,您可以请求仅获取标头(HEAD而不是GET)而没有实际的数据有效负载,这应该包括Content-Length.

如果你不能这样做,那么你需要开始下载和使用expectedContentLength.NSURLResponse


基本上,创建一个实例NSMutableURLRequest并调用参数设置为(setHTTPMethod:以替换默认值)。然后在您当前请求完整数据集(相同的 URL)时将其发送到服务器。method@"HEAD"GET

于 2013-10-28T10:23:29.987 回答
6

这是代码:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:candidateURL];
                    [request setHTTPMethod:@"HEAD"];

                    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
                    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
                     {
                         NSLog(@"Content-lent: %lld", [operation.response expectedContentLength]);

                     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                         NSLog(@"Error: %@", error);
                     }];
于 2014-09-07T13:02:29.183 回答