Home > Enterprise >  Convert a UTF-8 String to ISO-8859-15/Latin-9 in Swift
Convert a UTF-8 String to ISO-8859-15/Latin-9 in Swift

Time:09-26

I have some user input that needs to be sent to an HTTP-API which expects ISO-8859-15 (Latin-9) encoding. I use Alamofire to contact the API. The user input is a normal UTF-8 String (named "text" in this case):

let parameters: [String: String] = [
  ...
  "message": String(data: text.data(using: .windowsCP1252)!, encoding: .windowsCP1252)!,
  ...
]

session.request("URL", method: .post, parameters: parameters).validate().responseString { response in
  ...
}

I tried a few of the available encodings (.isoLatin1, .isoLatin2, windowsCP1252, windowsCP1250) but none seems to work correctly (for german characters like ö, ä and ü).

Any ideas? Thanks in advance for any tips.

CodePudding user response:

There is a larger list of CFStringEncodings and each of them can be converted to a String.Encoding.

For ISO 8859-15 we need CFStringEncodings.isoLatin9:

let cfEnc = CFStringEncodings.isoLatin9
let nsEnc = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(cfEnc.rawValue))
let isoLatin9encoding = String.Encoding(rawValue: nsEnc) // String.Encoding

Conversion test:

let s = "äöü€ŠšŽžŒœŸ"
if let d = s.data(using: isoLatin9encoding) {
    print(d.map { String(format: "hhX", $0) }.joined(separator: " "))
    // E4 F6 FC A4 A6 A8 B4 B8 BC BD BE
}

You can also define a static computed property

extension String.Encoding {
    static var isoLatin9: String.Encoding {
        let cfEnc = CFStringEncodings.isoLatin9
        let nsEnc = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(cfEnc.rawValue))
        return String.Encoding(rawValue: nsEnc)
    }
}

and use it as

if let d = s.data(using: .isoLatin9) { ... }
  • Related