NSString中的Unicode十六进制字符代码不显示

时间:2016-07-13 22:24:28

标签: ios objective-c unicode nsstring

我从服务器请求中收到Unicode十六进制字符代码&#x1f682,我想将其转换为UILabel中的Steam Locomotive表情符号。我已经阅读了很多关于这个问题的其他帖子,但没有一个解决方案似乎有效。

我已阅读有关解码HTML实体或将NSString设置为UFT8字符串的帖子,但这些都不起作用。

NSString *unicode = @"Train &#x1f682";
self.label.text = [unicode stringByDecodingHTMLEntities]; <---- Doesn't work

试过这个:

NSString *train = @"Train &#x1f682";
self.label.text = [NSString stringWithUTF8String:[train UTF8String]]; <---- Doesn't work

有关如何转换此内容的任何想法,以便我可以在UILabel中看到表情符号

注意:这与其他有关unicode字符的问题不同,因为此格式尚未得到解决,并提出了解决方案。

1 个答案:

答案 0 :(得分:0)

我使用以下方法开始工作:

- (void)viewDidLoad {
    [super viewDidLoad];

    self.label.text = [self convertHexUnicodeString:@"This is a train &#x1f682 I like trains! &#x1f682"];

}

- (NSString *)convertHexUnicodeString:(NSString *)unicodeText {

    NSScanner *myScanner;
    NSString *text = nil;
    myScanner = [NSScanner scannerWithString:unicodeText];

    while ([myScanner isAtEnd] == NO) {

        [myScanner scanUpToString:@"&#x" intoString:NULL] ;
        [myScanner scanUpToString:@" " intoString:&text] ;
        unicodeText = [unicodeText stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@", text] withString:[self replaceHexUnicode:text]];
    }

    unicodeText = [unicodeText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

    return unicodeText;
}

- (NSString *)replaceHexUnicode:(NSString *)text {

    text = [text substringFromIndex:3];

    unsigned unicodeInt = 0;
    [[NSScanner scannerWithString:text] scanHexInt:&unicodeInt];
    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;

    return [[NSString alloc] initWithBytes:chars length:len encoding:NSUTF32StringEncoding];

}