iosswiftalamofireafnetworking-3

Why am I getting 'Content-Length' with AFNetworking but not with Alamofire?


In Swift (Alamofire) I do this code:

let url = URL(string: "http://cdn.thechivemobile.com.edgesuite.net/v5/chive/20117177/20117177_2_600_366.gif")!
let task = Alamofire.request(url)
task.downloadProgress() { (progress) in
    print("*** \(progress.completedUnitCount) \(progress.totalUnitCount)\n")
}

And progress.totalUnitCount is always -1.

But with this Objective-C (AFNetworking) code:

NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://cdn.thechivemobile.com.edgesuite.net/v5/chive/20117177/20117177_2_600_366.gif"]];
AFHTTPRequestOperation *httpOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[httpOperation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {

    NSLog(@"*** %@", @(((double)totalBytesRead) / ((double)totalBytesExpectedToRead)));
}];
[httpOperation start];

totalBytesExpectedToRead is valid. I looked at the headers and they are slightly different. The Objective-C code gets headers with Content-Length, the Swift code does not.


Solution

  • The problem was I needed to add "Accept-Encoding: gzip" for Alamofire. I didn't need to do this with AFNetworking.

    request.addValue("gzip", forHTTPHeaderField: "Accept-Encoding")
    

    It seems Akamai is probably caching these images as zipped objects and unzipping them before downloading them. When it does this it doesn't know the unzipped content size ahead of time so it doesn't include "Content-Length".