2

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

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

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

如果我有 url,如何正确获取文件大小?

4

1 回答 1

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:

于 2013-04-10T08:56:54.160 回答