19

How to convert string to unicode(UTF-8) string in Swift?

In Objective I could write smth like that:

NSString *str = [[NSString alloc] initWithUTF8String:[strToDecode cStringUsingEncoding:NSUTF8StringEncoding]];

how to do smth similar in Swift?

Dirder
  • 363
  • 2
  • 3
  • 11
  • Maybe you can change how you decode it when you receive it? Like http://stackoverflow.com/questions/31733254/alamofire-returns-wrong-encoding , is this similar? – Eric Aya May 07 '16 at 11:55
  • Thanks, but it does not fit for me. simply speaking I need to convert this : let string = "ÐаÑпаÑи пÑогÑали ÑÑÑбоÐ" to this let result = "Карпати програли футбол" . I did it with online converters converting to Unicode(UTF-8) – Dirder May 07 '16 at 12:15

3 Answers3

16

Swift 4 and 5 I have created a String extension

extension String {
    func utf8DecodedString()-> String {
        let data = self.data(using: .utf8)
        let message = String(data: data!, encoding: .nonLossyASCII) ?? ""
        return message
    }
    
    func utf8EncodedString()-> String {
        let messageData = self.data(using: .nonLossyASCII)
        let text = String(data: messageData!, encoding: .utf8) ?? ""
        return text
    }
}
Gurjinder Singh
  • 9,221
  • 1
  • 66
  • 58
14

Swift 4:

let str = String(describing: strToDecode.cString(using: String.Encoding.utf8))
Patrick Mevzek
  • 10,995
  • 16
  • 38
  • 54
Alessandro Ornano
  • 34,887
  • 11
  • 106
  • 133
11

Use this code,

let str = String(UTF8String: strToDecode.cStringUsingEncoding(NSUTF8StringEncoding))

hope its helpful

Iyyappan Ravi
  • 3,205
  • 2
  • 16
  • 30
  • thanks, but this way does solve my problem. I like before got incorrectly displayed not Latin symbols :-( – Dirder May 07 '16 at 10:39
  • I have a string like this: " @ Rock-ЦиÑаÑа: Deep Purple " with unicode symbols (cyrilic etc). When I use online converter to Unicode(UTF-8) I can convert that to this: "@ Rock-Цитата: Deep Purple" Question is: How to do that in Swift? – Dirder May 07 '16 at 10:52
  • simply speaking I need to convert this : let string = "ÐаÑпаÑи пÑогÑали ÑÑÑбоÐ" to this let result = "Карпати програли футбол" . I did it with online converters converting to Unicode(UTF-8) – Dirder May 07 '16 at 12:10
  • what is the online converter please mention here and from what format to UTF-8 please mention the two formats also – Tyson Vignesh May 07 '16 at 12:23
  • 7
    `let cString = qString.cString(using: String.Encoding.utf8)` – Manish Nahar Apr 26 '17 at 08:00