revolutionkpi revolutionkpi - 6 months ago 39
iOS Question

How get file size with url?

In my iPhone application I need to get the file size, but I have only url of it.

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 lonLongValue];

How can I correctly get file size if I have url ?


Use NSURLConnection with Head request, the response will have expectedContentLength:


NSMutableURLRequest * req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@""]];
[req setHTTPMethod:@"Head"];
NSURLConnection * con = [[NSURLConnection alloc] initWithRequest:req
[con start];
[con release];


- (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: