revolutionkpi revolutionkpi - 4 months ago 16
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 ?

Answer

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

Request

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

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: