7

I'm trying to encode and decode Emojis to send them to my database.

I use this to encode:

var comentario = String()
let data = Comment.data(using: String.Encoding.nonLossyASCII, allowLossyConversion: true)
if let data = data {
    let emojiString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String
    comentario = emojiString
}

And it works. But now I don't know how to decode the emoji.

This is the type of encode ---> \ud83d\ude1a

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • 1
    Have you checked [this](https://gist.github.com/NarayanaRao35/3a69527a746e6cd688c21838e38e2e21) out? – Jože Ws May 27 '17 at 22:05
  • Because Im not able to touch the server side, so if they are using one type of encoding I need to do the same :/ –  May 28 '17 at 14:23
  • Thanks Jose it help me your link –  May 28 '17 at 14:58
  • 1
    If you want to answer your own question then post the solution as an *answer,* not as an edit to the question. I have therefore taken the liberty to undo your last edit. – Martin R May 29 '17 at 07:34
  • done, thanks for the advice –  May 29 '17 at 16:03

2 Answers2

29

Your encoding code can be simplified to

func encode(_ s: String) -> String {
    let data = s.data(using: .nonLossyASCII, allowLossyConversion: true)!
    return String(data: data, encoding: .utf8)!
}

Note that it encodes all non-ASCII characters not only Emojis (as \uNNNN where NNNN is the hexadecimal code of the Unicode character, or as \NNN where NNN is an octal code). Decoding is done by reversing the transformations:

func decode(_ s: String) -> String? {
    let data = s.data(using: .utf8)!
    return String(data: data, encoding: .nonLossyASCII)
}

This returns an optional because it can fail for invalid input.

Example:

let s = "Hello ."
let e = encode(s)
print(e) // Hello \ud83d\ude03.

if let d = decode(e) {
    print(d) // Hello .
}

Of course you can also define the code as extension methods of the String type, and you might want to choose better function names.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
0

I fixed this. If you have a server with encode utf8mb4, then for encoding emojis use this code:

var comentario = String()
let data = Comment.data(using: String.Encoding.nonLossyASCII, allowLossyConversion: true)
if let data = data {
    let emojiString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String
    comentario = emojiString
}// comentario contains the emoji encoded

DECODING:

let data = comentarios.data(using: String.Encoding.utf8, allowLossyConversion: false)

    if data != nil{
        let valueunicode = NSString(data: data!, encoding: String.Encoding.nonLossyASCII.rawValue) as? String

        if valueunicode != nil{
            comentarios = valueunicode!
        }
    }//comentarios contantes the deecode string(emoji)