Search code examples
iosobjective-cnsurlsessionnsurlsessiondownloadtask

ios objective c : How to get NSURLSession to return Content-Length(http header) from server


I already tried
How to get NSURLSession to return Content-Length(http header) from server. Objective-c, ios

- (long long) getContentLength
{
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
    request.HTTPMethod = @"HEAD";
    [request addValue:@"identity" forHTTPHeaderField:@"Accept-Encoding"];

    NSURLSessionDownloadTask *uploadTask
    = [session downloadTaskWithRequest:request
                     completionHandler:^(NSURL *url,NSURLResponse *response,NSError *error) {
                         NSLog(@"handler size: %lld", response.expectedContentLength);
                       totalContentFileLength = [[NSNumber alloc] initWithFloat:response.expectedContentLength].longLongValue;

                     }];
    NSLog(@"content length=%lld", totalContentFileLength);
    [uploadTask resume];
    return totalContentFileLength;
}

I am getting always 0 from return value.


Solution

  • It's because you are returning value of function outside the completion handler, so your function is returns value before it's got response from server. Now you can't return value from completion handler. So you need to create method which have custom completion handler as parameter something like,

     - (void) getContentLength : (void(^)(long long returnValue))completionHandler
     {
    
    
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
    request.HTTPMethod = @"HEAD";
    [request addValue:@"identity" forHTTPHeaderField:@"Accept-Encoding"];
    
    NSURLSessionDownloadTask *uploadTask
    = [session downloadTaskWithRequest:request
                     completionHandler:^(NSURL *url,NSURLResponse *response,NSError *error) {
    
                         NSLog(@"handler size: %lld", response.expectedContentLength);
                         totalContentFileLength = [[NSNumber alloc] initWithFloat:response.expectedContentLength].longLongValue;
    
                         completionHandler(totalContentFileLength);
    
                     }];
    NSLog(@"content length=%lld", totalContentFileLength);
    [uploadTask resume];
    
    }
    

    and you can call this method like,

       [self getContentLength:^(long long returnValue) {
    
        NSLog(@"your content length : %lld",returnValue);
    
    }];