iosalamofirealamofire-request

iOS Alamofire - Streaming JSON lines first response issue


Using Alamofire 4.9.0.

I am trying to implement handling streaming APIs in JSON lines format. 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. After that stream continues to normally respond with a new JSON line per response coming through the stream.

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. 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:

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

Solution

  • So the problem here was that the response header didn't have Content-Type set to application/json. When this header is not set properly, URLSession data task will buffer first 512 bytes of response.

    More info can be found here: https://developer.apple.com/forums/thread/64875