如何用url获取文件大小?

时间:2013-04-10 08:26:01

标签: iphone ios

在我的iPhone应用程序中,我需要获取文件大小,但我只有它的URL。

如果我有文件路径,我可以得到这样的大小:

NSDictionary* attributeDict = [[NSFileManager defaultManager] attributesOfItemAtPath:resourcePath error:nil];
NSNumber* fileSizeObj = [attributeDict objectForKey:NSFileSize];
long long fileSizeVal = [fileSizeObj longLongValue];

如果我有网址,我怎样才能正确获取文件大小?

1 个答案:

答案 0 :(得分:4)

NSURLConnection请求中使用Head,响应将有expectedContentLength

请求

NSMutableURLRequest * req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png"]];
[req setHTTPMethod:@"Head"];
NSURLConnection * con = [[NSURLConnection alloc] initWithRequest:req
                                                    delegate:self];
[con start];
[con release];

代表

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"didReceiveResponse (%lld)", response.expectedContentLength);
}

注意它可能是否定的:

#define NSURLResponseUnknownLength ((long long)-1)

对于NSURLSession,请使用接受NSURLRequest个对象作为参数的任务工厂方法,例如- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler: