Ktor Darwin engine not supporting chunked data reading

168 Views Asked by At

I have a problem with chunked transfer encoding in iOS. This is the KMM code:

private const val DEFAULT_BUFFER_SIZE: Int = 8 * 1024

internal val client = HttpClient()
    
fun readChunkedData(url: String, onChunk: (String) -> Unit): Job {
    val scope = MainScope()
    return scope.launch {
        client.preparePost(url).execute {
            val channel: ByteReadChannel = it.body()
            while (!channel.isClosedForRead) {
                val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
                val count = channel.readAvailable(buffer)
                if (count > 0) {
                   val trimmed = buffer
                      .take(count)
                      .map { c -> Char(c.toInt()) }
                      .toCharArray()

                    onChunk(trimmed.concatToString())
                }
            }
        }
    }
}

iOS use Darwin engine and Android Okhttp for Ktor

In Android this code works fine:

enter image description here

But in iOS is not working as expected (instead of reading chunks is awaiting the whole response):

enter image description here

Is any solution to fix it? I was trying to use CIO engine but getting another issue in iOS: TLS sessions are not supported on Native platform.

1

There are 1 best solutions below

2
On

I have identified the problem. For some reason, iOS is not treating the backend response as chunked when it receives a 'plain/text' content type.

However, once the backend response header was changed to:

Content-Type: application/octet-stream

it started to work properly:

enter image description here