ios - 将表情符号从 JSON 字符串转换为字符

标签 ios swift swift4 emoji

我正在尝试将表情符号编码字符串从 JSON 字符串转换为字符。有些表情符号正在转换,有些则没有。

我正在使用的功能:

extension String {
var decodeEmoji: String? {
    let data = self.data(using: String.Encoding.utf8)
    let decodedStr = NSString(data: data!, encoding: String.Encoding.nonLossyASCII.rawValue)
    if decodedStr != nil {
        return decodedStr as String?
    }
    return self
    }
}


JSON string: Altre novità in arrivo oggi...  \ud83d\udcaa\ud83c\udffb

\ud83d\udcaa\ud83c\udffb”是💪🏻字符的表情符号字符串。

最佳答案

查看此answer或者为了显示情绪,您可以使用 NSAttributedString

NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[text dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];

例如,为 UILabel 创建扩展

@implementation UILabel (Emotion)

- (void)setHtmlText:(NSString *)text
{
    self.text = text;

    NSDictionary *attributes = [self.attributedText attributesAtIndex:0 longestEffectiveRange:nil inRange:NSMakeRange(0, self.attributedText.length)];

    NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithData:[text dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];

    [attrStr addAttributes:attributes range:NSMakeRange(0, attrStr.length)];

    self.attributedText = attrStr;
}

@end

关于ios - 将表情符号从 JSON 字符串转换为字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48276341/

相关文章:

swift - 如何在 mac os 的菜单栏应用程序中显示两行文本

ios - Swift/SpriteKit 多重碰撞检测?

ios - 如何知道用户在推送通知中点击了 "Don' t 允许”

ios - 将 ViewController 呈现为弹出窗口

ios - 在 Swift 上推送通知

swift - 将具有一种类型的结构更改为另一种类型

swift - 我的数据永远不会用可编码协议(protocol)填满我的类(class)

ios - 将阴影和角半径应用于 View ,而不是整个单元格

ios - 如何在具有 Google Cast 支持的 iOS 应用程序中获取定时元数据更新

ios - 自动布局大小的 UITableView 行中的垂直压缩歧义