Objective-c从URL检查文件大小而不下载

Kha*_*war 4 objective-c ios

我需要从URL检查文件的大小.使用AFNetworking下载文件时,我可以完美地获得文件大小.

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

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

                                                                        }];
Run Code Online (Sandbox Code Playgroud)

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

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

    }];
Run Code Online (Sandbox Code Playgroud)

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

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]);
Run Code Online (Sandbox Code Playgroud)

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

Wai*_*ain 21

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

如果你不能做到这一点,那么你需要开始下载和使用expectedContentLengthNSURLResponse.


基本上,创建的一个实例NSMutableURLRequest,并调用setHTTPMethod:与所述method参数集@"HEAD"(替换默认这是GET).然后在您当前请求提供完整数据集(相同的URL)时将其发送到服务器.


Has*_*jmi 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);
                     }];
Run Code Online (Sandbox Code Playgroud)