This question already has an answer here:
这个问题已经有了答案:
- Get remote file size via HTTP without downloading said file 1 answer
- 通过HTTP获取远程文件大小,而不需要下载文件1。
In my iPhone application I need to get the file size, but I have only url of it.
在我的iPhone应用程序中,我需要得到文件大小,但我只有它的url。
If I have file path I can get size like this:
如果我有文件路径,我可以得到这样的大小:
NSDictionary* attributeDict = [[NSFileManager defaultManager] attributesOfItemAtPath:resourcePath error:nil];
NSNumber* fileSizeObj = [attributeDict objectForKey:NSFileSize];
long long fileSizeVal = [fileSizeObj longLongValue];
How can I correctly get file size if I have url ?
如果我有url,如何正确地获取文件大小?
1 个解决方案
#1
4
Use NSURLConnection
with Head
request, the response will have expectedContentLength:
使用NSURLConnection与Head请求,响应将预期内容长度:
Request
请求
NSMutableURLRequest * req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://cdn.sstatic.net/*/img/apple-touch-icon.png"]];
[req setHTTPMethod:@"Head"];
NSURLConnection * con = [[NSURLConnection alloc] initWithRequest:req
delegate:self];
[con start];
[con release];
Delegate
委托
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"didReceiveResponse (%lld)", response.expectedContentLength);
}
Note it might be negative:
注意它可能是消极的:
#define NSURLResponseUnknownLength ((long long)-1)
For NSURLSession
, use tasks factory methods that are accepting NSURLRequest
objects as parameters, e.g. - (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler:
对于NSURLSession,使用工厂方法任务接受NSURLRequest对象作为参数,例如-(NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)请求completionHandler:(空白(^)(NSData *数据,NSURLResponse *反应,NSError *误差))completionHandler:
#1
4
Use NSURLConnection
with Head
request, the response will have expectedContentLength:
使用NSURLConnection与Head请求,响应将预期内容长度:
Request
请求
NSMutableURLRequest * req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://cdn.sstatic.net/*/img/apple-touch-icon.png"]];
[req setHTTPMethod:@"Head"];
NSURLConnection * con = [[NSURLConnection alloc] initWithRequest:req
delegate:self];
[con start];
[con release];
Delegate
委托
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"didReceiveResponse (%lld)", response.expectedContentLength);
}
Note it might be negative:
注意它可能是消极的:
#define NSURLResponseUnknownLength ((long long)-1)
For NSURLSession
, use tasks factory methods that are accepting NSURLRequest
objects as parameters, e.g. - (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler:
对于NSURLSession,使用工厂方法任务接受NSURLRequest对象作为参数,例如-(NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)请求completionHandler:(空白(^)(NSData *数据,NSURLResponse *反应,NSError *误差))completionHandler: