NSString到表情符号Unicode [英] NSString to Emoji Unicode

查看:109
本文介绍了NSString到表情符号Unicode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从包含表情符号的unicodes的后端提取JSON文件。这些不是传统的unicodes(例如:\\\),而是跨平台工作的unicodes(例如:\ U0001F604)。

I am trying to pull an JSON file from the backend containing unicodes for emoji. These are not the legacy unicodes (example: \ue415), but rather unicodes that work cross platform (example: \U0001F604).

这是一个示例片段json被拉了:

Here is a sample piece of the json getting pulled:

[
 {
 "unicode": "U0001F601",
 "meaning": "Argh!"
 },
 {
 "unicode": "U0001F602",
 "meaning": "Laughing so hard"
 }
]

我很难将这些字符串转换为在应用程序中显示为表情符号的unicodes。

I am having difficulty converting these strings into unicodes that will display as emoji within the app.

非常感谢任何帮助!

推荐答案

为了将这些unicode字符转换为NSString,你将会需要获取那些unicode字符的字节。

In order to convert these unicode characters into NSString you will need to get bytes of those unicode characters.

获取字节后,很容易用字节初始化NSString。下面的代码完全符合您的要求。假设 jsonArray 是从你的json中拉出来的 NSArray

After getting bytes, it is easy to initialize an NSString with bytes. Below code does exactly what you want. It assumes jsonArray is the NSArray generated from your json getting pulled.

// initialize using json serialization (possibly NSJSONSerialization)
NSArray *jsonArray; 

[jsonArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    NSString *charCode = obj[@"unicode"];

    // remove prefix 'U'
    charCode = [charCode substringFromIndex:1];

    unsigned unicodeInt = 0;

    //convert unicode character to int
    [[NSScanner scannerWithString:charCode] scanHexInt:&unicodeInt];


    //convert this integer to a char array (bytes)
    char chars[4];
    int len = 4;

    chars[0] = (unicodeInt >> 24) & (1 << 24) - 1;
    chars[1] = (unicodeInt >> 16) & (1 << 16) - 1;
    chars[2] = (unicodeInt >> 8) & (1 << 8) - 1;
    chars[3] = unicodeInt & (1 << 8) - 1;


    NSString *unicodeString = [[NSString alloc] initWithBytes:chars
                                                       length:len
                                                     encoding:NSUTF32StringEncoding];

    NSLog(@"%@ - %@", obj[@"meaning"], unicodeString);
}];

这篇关于NSString到表情符号Unicode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆