TransWikia.com

Can not convert umlauts (Ü Ö Ä ü ö ä è é) to .utf8

Stack Overflow Asked by Salome Tsiramua on November 7, 2021

I want to decode response from the http request. But getting error while encoding to .utf8

String(data: data, encoding: .utf8) returns nil when data contains umlauts from German language(Ü Ö Ä ü ö ä è é)

How can I decode the Data? object properly?

Edit:
Providing more details

This is how my response looks like. I can’t change it’s coming from backend similar to this.

let string = """
            {
            "test":"Value",
            "OperatingInfosQuotes":"n<div id="div_operatinginfo_inner">n<div id="div_operatinginfo_title"><b>Test</b></div>n<div id="div_operatinginfo_content">nn Ü Ö Ä ü ö ä è énn</div>n</div>n"
            }
            """
    
do {
  let encode = try JSONDecoder().decode(TestObject.self, from: Data(string.utf8))
  print(encode)
} catch {
  print("Count not decode")
}

And my codable object:

struct TestObject: Codable {
    var test: String
}

How can I handle it?

2 Answers

encoding: .windowsCP1252 helped.

The issue was that Json contains quotes ("") and it breaks the format of Json in Swift and couldn't convert to .utf8 as well.

If quotes will be removed from response everything will be okay, if not workaround is to convert to .windowsCP1252 string.

Answered by Salome Tsiramua on November 7, 2021

Your approach is completely wrong.

A Swift string has no encoding, it's just a sequence of characters. Your data contains bytes, which are characters stored in some encoding. You claim that the encoding is UTF8 which is apparently wrong.

There are two possibilities: One is that you know the encoding of the data and pass the correct one. The other is that if you don't know the encoding, you use a different function where you don't need to specify the encoding; instead the OS will look at the decoding and decide what is most likely the correct encoding. The result will only be nil if it is not any encoding that iOS understands.

Answered by gnasher729 on November 7, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP