Objective-c Check file size from URL without downloading

前端 未结 2 566
忘了有多久
忘了有多久 2020-12-16 07:09

I need to check the size of file from a URL. I get the file size perfectly when downloading file with AFNetworking.

AFHTTPRequestOperation *operation = [clie         


        
相关标签:
2条回答
  • 2020-12-16 07:25

    here is the code:

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:candidateURL];
                        [request setHTTPMethod:@"HEAD"];
    
                        AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
                        [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
                         {
                             NSLog(@"Content-lent: %lld", [operation.response expectedContentLength]);
    
                         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                             NSLog(@"Error: %@", error);
                         }];
    
    0 讨论(0)
  • 2020-12-16 07:26

    If the server supports it you can make a request to just get the headers (HEAD, as opposed to GET) without the actual data payload and this should include the Content-Length.

    If you can't do that then you need to start the download and use expectedContentLength of the NSURLResponse.


    Basically, create an instance of NSMutableURLRequest and call setHTTPMethod: with the method parameter set to @"HEAD" (to replace the default which is GET). Then send that to the server as you currently request for the full set of data (same URL).

    0 讨论(0)
提交回复
热议问题