Swift: Encoding and decoding emojis

Nowadays, you can meet emojis in every app, especially when you are having chat, comments and similar social features into your app. Emojis are Unicode values and need to be encoded and decoded when used. The simplest explanation would be, decode the Unicode when you need to show the emoji to the UI, and encode it when you need to send it to the server or store it locally.

Unicode is a computing industry standard for the consistent encoding, representation, and handling of text expressed in most of the world’s writing systems.

#1 Decoding the Unicode:

As previously mentioned, decoding the emoji is used when you want to show it to the UI (converts \ud83d\ude00 to 😀). You can show it in every component that supports text (UITextView, UILabel, UITextField).

extension String {
    var decodeEmoji: String{
        let data = self.data(using: String.Encoding.utf8);
        let decodedStr = NSString(data: data!, encoding: String.Encoding.nonLossyASCII.rawValue)
        if let str = decodedStr{
            return str as String
        }
        return self
    }
}

Usage

let decodedString = yourString.decodeEmoji

#2 Encoding the Unicode:

When we want to send an emoji message to the server, we can’t send it visually like 😀, so we need to convert it to its Unicode form \ud83d\ude00.

extension String {
    var encodeEmoji: String{
        if let encodeStr = NSString(cString: self.cString(using: .nonLossyASCII)!, encoding: String.Encoding.utf8.rawValue){
            return encodeStr as String
        }
        return self
    }
}

Usage

let encodedString = yourString.encodeEmoji


That’s it from this short tutorial, I hope this post helped you. If you have any comments please post them below, and also share to help others.

Leave a Reply

Your email address will not be published. Required fields are marked *