【问题标题】:NSString to Emoji UnicodeNSString 到 Emoji Unicode
【发布时间】:2014-08-30 23:45:21
【问题描述】:

我正在尝试从后端提取一个 JSON 文件,其中包含 emoji 的 unicode。这些不是旧的 unicode(例如:\ue415),而是跨平台工作的 unicode(例如:\U0001F604)。

这是一个被拉取的 json 示例:

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

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

非常感谢任何帮助!

【问题讨论】:

    标签: ios xcode unicode nsstring emoji


    【解决方案1】:

    为了将这些 un​​icode 字符转换为 NSString,您需要获取这些 un​​icode 字符的字节。

    得到字节后,很容易用字节初始化一个NSString。下面的代码完全符合您的要求。它假定jsonArray 是从您的json 被拉取生成的NSArray

    // 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);
    }];
    

    【讨论】:

    • 谢谢!这帮助我在过去几天取得了进展。现在我遇到了另一个需求:使用 U0001F601 格式将其转换回字符串。我遇到了许多涉及 \ue415 格式的答案,但不是 U0001F601 格式。对于这种方法,您是否也有方便的解决方案?
    • 您的 & 都不是必需的。当右移无符号数时,右移是逻辑(零填充)移位。无论如何,对 8 位 char 类型的赋值无论如何都会截断该值。即使它们是必需的,它们都应该是“0xFF”(或者如果你真的更喜欢,“((1
    猜你喜欢
    • 2014-09-02
    • 2021-05-17
    • 1970-01-01
    • 1970-01-01
    • 2021-08-16
    • 2017-02-18
    • 2011-11-27
    • 2011-11-13
    • 2015-09-25
    相关资源
    最近更新 更多