Alamofire是否支持分块数据响应?

时间:2015-06-12 11:29:08

标签: json swift alamofire chunked-encoding

目前尚不清楚Alamofire是否支持大型或渐进式数据集的分块数据。这是我的应用程序非常需要的功能,否则我可能需要研究其他方法。

Alamofire Github页面上,它指出Progress Closure & NSProgress,但我不确定这是什么。

根据Wikipedia关于Chunked数据传输的说明。

Senders can begin transmitting dynamically-generated content before knowing the total size of that content.


为了清楚起见,让我解释一下为什么我需要这个。

基本上我有一个部分缓存的非常大的JSON文件。完整的JSON文件由较小的JSON对象组成。我使用iojs / nodejs通过res.write()通过Express发送分块数据,Content-Length知道不发送html/js标头并将其作为分块数据发送。我已通过$conn = new mysqli("localhost", "root", "", "test"); $sql = "SELECT id, name, city FROM customers"; $results = mysqli_query($conn, $sql); $data = array(); while($row = mysqli_fetch_assoc($results)) { $data[] = $row; } $json = json_encode( $data ); echo $json; 验证了这项工作。


如果您希望我提供代码来证明这一点,请与我们联系。

3 个答案:

答案 0 :(得分:4)

在Alamofire中处理分块响应的正确方法是使用stream

    let req = Alamofire.request("http://localhost:8080")

    req.stream { (data) in
       print(String(data: data, encoding: String.Encoding.utf8) ?? "No data")
    }

答案 1 :(得分:1)

Alamofire肯定支持Transfer-Encoding: chunked数据,因为它已被NSURLSession支持。以下是从httpwatch.com下载分块图像的快速示例。

let request = Alamofire.request(.GET, "http://www.httpwatch.com/httpgallery/chunked/chunkedimage.aspx")
request.progress { bytesReceived, totalBytesReceived, totalBytesExpected in
    println("\(bytesReceived) - \(totalBytesReceived) - \(totalBytesExpected)")
}
request.response { request, response, _, error in
    println(request)
    println(response)
    println(error)
}

debugPrintln(request)

由于图片的内容长度不可用,totalBytesExpected将始终报告为-1,因为它未知。尽管如此报告了bytesReceivedtotalBytesReceived。在我看来,分块下载可能不是尝试向用户呈现下载进度的最佳候选者,因为它的长度不确定。

另一个可能有用的功能是请求中的新stream功能。它允许您在下载时存储每个数据块。

如果这些选项不能满足您的所有需求,请在我们的Github项目中提出您遇到的问题,以便我们进一步调查。

答案 2 :(得分:-1)

以下可能有帮助 -

https://github.com/Alamofire/Alamofire#downloading-a-file-wprogress

正在下载文件

Alamofire.download(.GET, "http://httpbin.org/stream/100", destination: destination)
         .progress { (bytesRead, totalBytesRead, totalBytesExpectedToRead) in
             println(totalBytesRead)
         }
         .response { (request, response, _, error) in
             println(response)
         }