Swift Encode/decode emojis

2019-01-17 18:50发布

问题:

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

回答1:

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 as \uNNNN, not only Emojis. 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