Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unnecessary decoding of UTF-8 in Swift (and possibly others) #626

Open
rassie opened this issue Jan 30, 2024 · 0 comments
Open

Unnecessary decoding of UTF-8 in Swift (and possibly others) #626

rassie opened this issue Jan 30, 2024 · 0 comments

Comments

@rassie
Copy link

rassie commented Jan 30, 2024

Swift generator currently produces this code:

import Foundation

let url = URL(string: "http://example.com/image.png")!

var request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
    if let error = error {
        print(error)
    } else if let data = data {
        let str = String(data: data, encoding: .utf8)
        print(str ?? "")
    }
}

task.resume()

In this code, received data is converted to UTF-8, which is only desirable if UTF-8 encoded text data is fetched. This is not always the case -- fetching binary data like images and also text data in different encodings (especially HTML with correctly set encoding) is quite common. Also, no UTF-8 conversion is done in most other examples, so if probably shouldn't be a thing in Swift either.

Possibly, a similar problem lies with Kotlin, which converts the response body to a string:

import java.io.IOException
import okhttp3.OkHttpClient
import okhttp3.Request

val client = OkHttpClient()

val request = Request.Builder()
  .url("http://example.com/image.png")
  .build()

client.newCall(request).execute().use { response ->
  if (!response.isSuccessful) throw IOException("Unexpected code $response")
  response.body!!.string()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

1 participant