【问题标题】:Swift - Alamofire totalBytesExpectedToRead returns -1 even Content-length is setSwift - 即使设置了 Content-length,Alamofire totalBytesExpectedToRead 也会返回 -1
【发布时间】:2017-02-12 07:25:22
【问题描述】:

即使 Content-length 有值,totalBytesExpectedToRead 也会返回 -1

我在 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

【问题讨论】:

    标签: ios swift alamofire


    【解决方案1】:

    在标头中传递 Accept-Encoding 密钥。

    它对我有用。

    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

    【讨论】:

      【解决方案2】:

      服务器发送给您的内容肯定有问题:宣布的Content-Length(163 字节)小于您实际收到的内容(1211 字节)。

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

      【讨论】:

      • 我会检查服务器。感谢@François 的回答
      猜你喜欢
      • 2016-09-30
      • 1970-01-01
      • 1970-01-01
      • 2019-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-18
      • 1970-01-01
      相关资源
      最近更新 更多