RunLoop
RunLoop

Reputation: 20376

Display Unicode String as Emoji

I currently receive emojis in a payload in the following format:

\\U0001F6A3\\U0000200D\\U00002640\\U0000FE0F

which represents "🚣‍♀️"

However, if I try to display this, it only shows the string above (escaped with 1 less ), not the emoji e.g.

NSString *emoji = payload[@"emoji"];
NSLog(@"%@", emoji) then displays as \U0001F6A3\U0000200D\U00002640\U0000FE0F

It's as if the unicode escape it not being recognised. How can I get the string above to show as an emoji?

Please assume that the format the data is received in from the server cannot be changed.

UPDATE

I found another way to do it, but I think the answer by Albert posted below is better. I am only posting this for completeness and reference:

NSArray *emojiArray = [unicodeString componentsSeparatedByString:@"\\U"];
NSString *transformedString = @"";

for (NSInteger i = 0; i < [emojiArray count]; i++) {

    NSString *code = emojiArray[i];
    if ([code length] == 0) continue;
    NSScanner *hexScan = [NSScanner scannerWithString:code];
    unsigned int hexNum;
    [hexScan scanHexInt:&hexNum];
    UTF32Char inputChar = hexNum;
    NSString *res = [[NSString alloc] initWithBytes:&inputChar length:4 encoding:NSUTF32LittleEndianStringEncoding];
    transformedString = [transformedString stringByAppendingString:res];
}

Upvotes: 0

Views: 827

Answers (2)

Albert Renshaw
Albert Renshaw

Reputation: 17892

Remove the excess backslash then convert with a reverse string transform stringByApplyingTransform. The transform must use key "Any-Hex" for emojis.

NSString *payloadString = @"\\U0001F6A3\\U0000200D\\U00002640\\U0000FE0F";
NSString *unescapedPayloadString = [payloadString stringByReplacingOccurrencesOfString:@"\\\\" withString:@"\\"];
NSString *transformedString = [unescapedPayloadString stringByApplyingTransform:@"Any-Hex" reverse:YES];

NSLog(@"%@", transformedString);//logs "🚣‍♀️"

Upvotes: 3

GeneCode
GeneCode

Reputation: 7588

I investigated this, and it seems you may not be receiving what you say you are receiving. If you see \U0001F6A3\U0000200D\U00002640\U0000FE0F in your NSLog, chances are you are actually receiving \\U0001F6A3\\U0000200D\\U00002640\\U0000FE0F at your end instead. I tried using a variable

NSString *toDecode = @"\U0001F6A3\U0000200D\U00002640\U0000FE0F";
self.tv.text = toDecode;

And in textview it is displaying the emoji fine. enter image description here

So you got to fix that first and then it will display well.

Upvotes: 1

Related Questions