Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display the emoji and special characters in UIlabel and UItextviews?

I am trying to display a string in all sorts of items such as UIlabel,UItextview,Uitextfield etc.....I am trying to do like this in a manner like this

NSData *data1 = [title dataUsingEncoding:NSUTF8StringEncoding];
NSString *goodValue = [[NSString alloc] initWithData:data1 encoding:NSNonLossyASCIIStringEncoding];
label.text=goodvalue;

this is working sometimes for me ,but some times it returns null for the string like this "Youtube\ud83d\ude27\ud83d\ude2e\ud83d\ude2f\ud83d".Can anybody guide me on this?

like image 614
hacker Avatar asked Dec 20 '22 14:12

hacker


1 Answers

Emoji characters are in unicode plane 1 and thus require more than 16 bits to represent a code point. Thus two UTF8 representations or one UTF32 representation. Unicode is actually a 21-bit system and for plane 0 characters (basically everything except emoji) 16 bits is sufficient and we get by using 16 bits. Emoji need more than 16 bits.

"Youtube\ud83d\ude27\ud83d\ude2e\ud83d\ude2f\ud83d". is invalid, it is part of a utf16 unicode escaped string, the last \ud83d is 1/2 of an emoji character.

Also, inorder to create a literal string with the escape character "\" the escape character must be escaped: "\\".

NSString *emojiEscaped = @"Youtube\\ud83d\\ude27\\ud83d\\ude2e\\ud83d\\ude2f";
NSData *emojiData = [emojiEscaped dataUsingEncoding:NSUTF8StringEncoding];
NSString *emojiString = [[NSString alloc] initWithData:emojiData encoding:NSNonLossyASCIIStringEncoding];
NSLog(@"emojiString: %@", emojiString);

NSLog output:

emojiString: Youtube😧😮😯

The emoji string can also be expressed in utf32:

NSString *string = @"\U0001f627\U0001f62e\U0001f62f";
NSLog(@"string: %@", string);

NSLog output:

string1: 😧😮😯

like image 66
zaph Avatar answered Dec 22 '22 03:12

zaph