Swift - Alamofire totalBytesExpectedToRead返回-1甚至Content-length设置为

时间:2016-10-04 07:55:55

标签: ios swift alamofire

totalBytesExpectedToRead返回-1,甚至Content-length的值为

我在stackoverflow上找到了相同的problem,但没有回答

这是我的代码:

Alamofire.download(.POST, urlString, headers: headers, destination: destination)   
       .progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
            print("totalBytesRead: \(totalBytesRead)")
            print("totalBytesExpectedToRead: \(totalBytesExpectedToRead)\n\n")
        }
        .response { request, response, data, error in
        }

服务器响应:

Access-Control-Allow-Origin →*
Access-Control-Expose-Headers →Link
Connection →keep-alive
Content-Length →163
Content-Type →application/json; charset=utf-8
Date →Tue, 04 Oct 2016 07:12:56 GMT

结果:

totalBytesRead: 1211
totalBytesExpectedToRead: -1

2 个答案:

答案 0 :(得分:1)

服务器发送给你的东西肯定有问题:宣布的Content-Length(163字节)小于实际接收的数量(1211字节)。

似乎只有一个调用进度块,我会说Alamofire将totalBytesExpectedToRead设置为-1,以响应服务器宣布的内容与收到的内容之间的不一致。 / p>

答案 1 :(得分:0)

在标头中传递接受编码键。

对我有用。

let headers = ["Accept-Encoding" : ""]

Alamofire.download(.POST, urlString, headers: headers, destination: destination)   
       .progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
            print("totalBytesRead: \(totalBytesRead)")
            print("totalBytesExpectedToRead: \(totalBytesExpectedToRead)\n\n")
        }
        .response { request, response, data, error in
        }

Check accepted answer