NSString to Emoji Unicode

前端 未结 1 1001
名媛妹妹
名媛妹妹 2020-12-10 22:23

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 p

相关标签:
1条回答
  • 2020-12-10 23:08

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

    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);
    }];
    
    0 讨论(0)
提交回复
热议问题