amleszk
amleszk

Reputation: 6290

finding the download size of a URL (Content-Length)

I'm looking for some objective-c code to query a URL and give the download size, similar to this example: Checking Download size before download

but in objective-c, and using ASIHttp is OK.

Upvotes: 2

Views: 2431

Answers (3)

Yuchen
Yuchen

Reputation: 33036

New since iOS 9, should use NSURLSession instead of NSURLConnection which is deprecated:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:@"http://www.google.com/"
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:10];
[request setHTTPMethod:@"HEAD"];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config
                                                      delegate:nil
                                                 delegateQueue:queue];
[[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
  {
      NSLog(@"%lld", response.expectedContentLength);
  }] resume];

Upvotes: 0

Andy Friese
Andy Friese

Reputation: 6489

Initiate the HTTP HEAD request:

NSURL *url = [NSURL URLWithString:@"http://www.google.com/"];
NSMutableURLRequest *httpRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
[httpRequest setHTTPMethod:@"HEAD"];
NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:httpRequest delegate:self];

Implement the delegate:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)aResponse {
   long long filesize = [aResponse expectedContentLength];
}

Upvotes: 6

user207421
user207421

Reputation: 310913

The answer is the same. HTTP HEAD request. There is nothing language-specific in the post you cited.

Upvotes: 0

Related Questions