简体   繁体   English

iOS Alamofire - 流式传输 JSON 线路第一响应问题

[英]iOS Alamofire - Streaming JSON lines first response issue

Using Alamofire 4.9.0.使用 Alamofire 4.9.0。

I am trying to implement handling streaming APIs in JSON lines format.我正在尝试以 JSON 行格式实现处理流 API。 Here's how:就是这样:

stream = Alamofire.request(url, method: HTTPMethod.get,
                           headers: TTSessionManager.headers)
    .validate()
    .stream(closure: { (data) in
        // parsing JSON lines ...
    })
    .response(completionHandler: { (response) in
        // error handling ...
    })

Now the issue is that the first response takes some time to return.现在的问题是第一个响应需要一些时间才能返回。 And when it does I get a couple of JSON lines in one big batch.当它完成时,我会在一大批中获得几条 JSON 线。 After that stream continues to normally respond with a new JSON line per response coming through the stream.之后,stream 继续正常响应,每个响应通过 stream 发出一条新的 JSON 线。

Has anyone encountered this behaviour?有没有人遇到过这种行为? I'm wondering wether there is some additional session or request setup needed in order for this to work normal (line per response) from the start.我想知道是否还有一些额外的 session 或请求设置,以便从一开始就正常工作(每个响应行)。 When inspecting the response.metrics after canceling the request a lot of the fields are null so I can't for sure say wether some of the initial connection steps are the issue:在取消请求后检查response.metrics时,很多字段都是 null 所以我不能肯定地说一些初始连接步骤是否是问题:

(Domain Lookup Start) (null)
(Domain Lookup End) (null)
(Connect Start) (null)
(Secure Connection Start) (null)
(Secure Connection End) (null)
(Connect End) (null)

So the problem here was that the response header didn't have Content-Type set to application/json .所以这里的问题是响应 header 没有将Content-Type设置为application/json When this header is not set properly, URLSession data task will buffer first 512 bytes of response.当此 header 设置不正确时,URLSession 数据任务将缓冲前 512 个字节的响应。

More info can be found here: https://developer.apple.com/forums/thread/64875更多信息可以在这里找到: https://developer.apple.com/forums/thread/64875

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM