我正在寻找一种方法来获取 NSURL 地址中特定文件的文件大小。这是我尝试过的,但它总是在日志输出中返回“0”:
NSString *url = @"http://www.examplesite.com/file01.zip";
unsigned long long fileSize1 = [[[NSFileManager defaultManager] attributesOfItemAtPath:[url lastPathComponent] error:nil] fileSize];
NSLog(@"size of %@ in bytes === %llu", [url lastPathComponent], fileSize1);
Run Code Online (Sandbox Code Playgroud)
在搜索了一些之后,我找到了这个解决方案。它在服务器上查找文件的文件大小并在日志中显示结果。
NSString *url = @"http://www.examplesite.com/file01.zip";
NSURL *URL = [NSURL URLWithString:url];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"HEAD"];
NSHTTPURLResponse *response;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error: nil];
long long size = [response expectedContentLength];
NSLog(@"File size before download: %lld",size);
Run Code Online (Sandbox Code Playgroud)