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()
}
Swift generator currently produces this code:
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: