Wednesday, February 17, 2016

Objective C displaying emoji characters in UILabel

Ever since I started using chat applications (like Whats app, We chat....) I was always wondered about the emoticons usage in the chat applications.
I came to know the importance and usage of those icons once I started developing
a chat applications for one of my clients. These icons are very useful for 
expressing our feelings in a simple and easy way instead of writing paragraphs
to our buddies in the chat.

While developing my chat application, I was able to pass simple text but I was 
stuck at passing these emoji icons which are uncoded values. For images, I have
converted them to binary data and sent across as string and at the receiver end 
I am converting binary data back to image. This process is fine for images,
where as for emoji icons, this process is not appropriate and we can't send them
as images to the chat servers. So I started searching for an encoding and 
decoding process for these emoji characters.

All we have to do for passing these icons at sender and receiver ends of 
a chat applications is to do NSNonLossyASCIIStringEncoding. Sounds so simple now, 
but it took me couple of days to me for googling and for R&D for this 
functionality. I have shared my Objective c code for quick usage in your 
chat applications.

I used the below code to encode emoji character in Objective c. I have taken 
the enter emoji character to a NSString and converted it to NSData using NonLossyASCIIStringEncoding.


NSString *uniText = [NSString stringWithUTF8String:[textview.text UTF8String]]; 
NSData *msgData = [uniText dataUsingEncoding:NSNonLossyASCIIStringEncoding]; 
NSString *goodMsg = [[NSString alloc] initWithData:msgData encoding:NSUTF8StringEncoding];

And the below code to decode and display in UILabel using Objective c. I have 
taken the received chat message body to char array and converted it to NSData 
and then converted it to NSString using the same encoding that we have done at 
the time of sending. As the final conversion is NSString, we can use it in all the 
UI controls (UILabel, UITextField....) for display.


const char *jsonString = [body UTF8String]; 
NSData *data = [NSData dataWithBytes: jsonString length:strlen(jsonString)]; 
NSString *msg = [[NSString alloc] initWithData:data encoding:NSNonLossyASCIIStringEncoding];

Feel free to comment in case of any queries or concerns.

Enjoy emoji icons sharing in your iOS chat applications :)