There is an image file in the server. I would like to know the size of the image without downloading it from the server.
Asked
Active
Viewed 772 times
0
-
http://stackoverflow.com/questions/18386990/get-size-file-nsurlconnection look at this – Sport Feb 28 '14 at 06:37
-
1You need to make a `HEAD` type request to the URL and read the `Content-Length` key-value from the response headers. Check [this answer](http://stackoverflow.com/a/19317092/1407017) – Amar Feb 28 '14 at 06:40
-
possible duplicate of [How to find size of a file before downloading it in iOS 7?](http://stackoverflow.com/questions/19315533/how-to-find-size-of-a-file-before-downloading-it-in-ios-7) – Amar Feb 28 '14 at 07:22
2 Answers
1
You'll want to do a HEAD request instead of a GET request. Then you'll check the Content-Length to get the size.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"HEAD"];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
NSLog(@"Size: %@", [[httpResponse allHeaderFields] objectForKey:@"Content-Length"]);
}];
Note that [[response allHeaderFields] objectForKey:@"Content-Length"]
will return either an NSNumber or an NSString, not a primitive (I'm not sure which, you'll have to test it, or maybe someone else can comment on that).
Update
[response expectedContentLength]
is an easier way to get the content length once you've made the request. And that one returns a long long
instead of an NSNumber or NSString.

IOS Learner
- 75
- 4

Ray Lillywhite
- 746
- 5
- 12
0
Use NSMutableURLRequest to send request and In Delegate Methods
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
long expectedlength=[response expectedContentLength];
}
I hope it will works..!

Dinesh Reddy Chennuru
- 491
- 5
- 10