NSString to Emoji Unicode

假装没事ソ 提交于 2019-11-27 06:27:46

问题


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).

Here is a sample piece of the json getting pulled:

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

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

Any help is greatly appreciated!


回答1:


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



回答2:


// String to unicode

if let data = NormalString.data(using: String.Encoding.nonLossyASCII), let convertedString = String.init(data: data, encoding: String.Encoding.utf8) { return convertedString }

//Unicode to string

if let data = UnicodeString.data(using: String.Encoding.utf8), let convertedString = String.init(data: data, encoding: String.Encoding.nonLossyASCII) { return convertedString }



来源:https://stackoverflow.com/questions/24662336/nsstring-to-emoji-unicode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!