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

11,369

Solution 1

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: 😧😮😯

Solution 2

NSString *str = @"Happy to help you \U0001F431";

NSData *data = [str dataUsingEncoding:NSNonLossyASCIIStringEncoding];
NSString *valueUnicode = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];


NSData *dataa = [valueUnicode dataUsingEncoding:NSUTF8StringEncoding];
NSString *valueEmoj = [[NSString alloc] initWithData:dataa encoding:NSNonLossyASCIIStringEncoding];

_lbl.text = valueEmoj;
Share:
11,369
hacker
Author by

hacker

Updated on June 04, 2022

Comments

  • hacker
    hacker almost 2 years

    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?