I'm using NSURLSession et al to download files in my iPhone app. It works correctly except for large (>20MB) files. Then, without exception, the
NSURLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:
callback returns -1 for totalBytesExpectedToWrite.
Embedded in the NSURLSessionDownloadTask.response object there is an HTTP header dictionary with this key/value pair:
"Content-Length" = (
22268238
);
This is the correct value that I need so I can monitor the download progress, not the "expected value".
How can I obtain this header value from the NSURLResponse object? If I access response.expectedContentLength it always returns -1.
One would expect a -allHeaderFields method, or perhaps
[response headerValueForKey:@"Content-Length"] or some such.
Is there a way to obtain the NSURLResponse object's HTTP header values in a NSDictionary?
NSURLSession does not have any logic that changes based on the size of the incoming file. I suspect that this change in behaviour is driven by your server. That is, at a certain threshold the server switches to the chunked transfer encoding, at which point NSURLSession has no idea how much data is expected. That’s why expectedContentLength is returning NSURLResponseUnknownLength.
If you happen to know that the server sets Content-Length to a valid value — which it’s not required, or even encouraged to do when using the chunked encoding — feel free to get that header and rely on it.
How can I obtain this header value from the
NSURLResponseobject?
Is the -valueForHTTPHeaderField: method not working for you?
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"