【发布时间】:2019-07-26 06:14:15
【问题描述】:
我尝试从dweet.io 服务收听数据。 我使用listen 方法实时获取数据。它使用分块的 HTTP 响应。
我为此创建了简单的网络管理器
import Foundation
class NetworkManager: NSObject, URLSessionDataDelegate {
private lazy var session = URLSession(configuration: .default, delegate: self, delegateQueue: .main)
private lazy var task = self.session
.dataTask(with: URL(string: "https://dweet.io/listen/for/dweets/from/opposite-carpenter")!)
func start() {
self.task.resume()
}
// THIS METHOD IS NEVER CALLED
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
print(data)
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
print(error!.localizedDescription)
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
print(response)
completionHandler(.allow)
}
}
当我启动它时,我永远不会得到数据。但是,我收到了 200 个状态代码和标题的响应。大约一分钟后,我收到一个错误 The network connection was lost.
同时我用curl 做同样的事情。它正在按预期获取数据。
curl -i "https://dweet.io/listen/for/dweets/from/subdued-nation"
我感到困惑的另一件事是 iOS 应用程序和 curl 在标题中的 Transfer-Encoding 字段中向我显示了不同的值:
UrlSession 返回"Transfer-Encoding" : "Identity"。
同时 curl 显示Transfer-Encoding: chunked(这是预期的)。
我尝试应用this answer 中描述的方法,但得到了相同的结果。
【问题讨论】:
-
让我们确保问题出在 URL 而不是您的代码上。如果将
URL(string: "https://dweet.io/listen/for/dweets/from/opposite-carpenter")更改为URL(string: "https://www.apple.com"),数据是否会打印到控制台中? -
你也说“大约一分钟后”。这听起来像是您正在超时,因为一分钟正是 URLSessionConfiguration
timeoutIntervalForRequest的默认值。这是一个需要保持打开更长时间的连接吗? -
@matt 你是对的。如果我使用 apple.com 作为 url,那就可以了。因为那是普通的 HTTP 请求。但是如何处理 HTTPS 流?
标签: swift http chunked-encoding urlsession http-chunked