Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSURLConnection expectedContentLength returns -1

I'm trying to view the progress bar while downloading a file. The file is generated through PHP, I'm sending the "Content-length" header, which actually works.

The file is downloaded OK so that's not the problem. Unfortunately I just can't get the file size in order to properly display the progress bar.

Here is my code:

write_to_filename = [issue objectForKeyedSubscript:filename];
NSString *post =[[NSString alloc] initWithFormat:@"user_id=%@&email=%@&password=%@",[userData stringForKey:@"userId"],[userData stringForKey:@"email"],[userData stringForKey:@"password"]];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://MY_API_REQUEST"]];

NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

[request setValue:@"application/pdf" forHTTPHeaderField:@"Accept"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];
[NSURLConnection connectionWithRequest:request delegate:self];

[issueArray writeToFile:[self saveFilePath] atomically:YES];

The NSURLConnection

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse 

*)response {

    NSLog(@"%lld",[response expectedContentLength]);
    _responseData = [[NSMutableData alloc] init];

}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [_responseData appendData:data];
}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
                  willCacheResponse:(NSCachedURLResponse*)cachedResponse {

    return nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *fileName = [[paths objectAtIndex:0] stringByAppendingPathComponent:write_to_filename];
    [_responseData writeToFile:fileName atomically:YES];

    write_to_filename = nil;
    _responseData = nil;

    [[self IssuesOverviewCollection] reloadData];

}

I've tried many different things, unfortunately it's not working and keeps return -1.

like image 923
GSK1985 Avatar asked Jan 11 '23 13:01

GSK1985


1 Answers

This can happen if your server is employing compression (which it can do transparently). You can turn off compression on the server by changing your request Accept-Encoding parameter:

[request setValue:@"identity" forHTTPHeaderField:@"Accept-Encoding"];
like image 125
Rob Avatar answered Jan 26 '23 00:01

Rob