带有表情符号的文本未解码 - iOS Swift

Text with emoji is not decoding - iOS Swift

我使用下面的代码 encode/decode 包含表情符号的字符串。

extension String {
    func encodeEmoji() -> String {
        let data = self.data(using: .nonLossyASCII, allowLossyConversion: true)!
        return String(data: data, encoding: .utf8)!
    }

    func decodeEmoji() -> String? {
        let data = self.data(using: .utf8)!
        return String(data: data, encoding: .nonLossyASCII)
    }
}

我在下面这样调用了这个函数。转换了 'User' 模型中的响应。

let user = User() // Loaded API's response in this model
let textWithEmoji = user.aboutMe.decodeEmoji() //Here, I am getting the string as the same as before decoding
lblAboutMe.text = textWithEmoji

以下是未解码的编码字符串:

"I love too...\n\u2705 Laugh \uD83D\uDE02\n\u2705 Read novels \uD83D\uDCDA\n\u2705 Watch movies \uD83C\uDFAC\n\u2705 Go for bike rides \uD83D\uDEB5\uD83C\uDFFD\u200D\u2640\uFE0F\n\u2705 Go for long walks \uD83D\uDEB6\uD83C\uDFFD\u200D\u2640\uFE0F\n\u2705 Cook \uD83D\uDC69\uD83C\uDFFD\u200D\uD83C\uDF73\n\u2705 Travel \uD83C\uDDEA\uD83C\uDDFA\uD83C\uDDEE\uD83C\uDDF3\uD83C\uDDEC\uD83C\uDDE7\n\u2705 Eat \uD83C\uDF2E\uD83C\uDF5F\uD83C\uDF73\n\u2705 Play board games \u265F\n\u2705 Go to the theatre \uD83C\uDFAD\nMy favourite season is autumn \uD83C\uDF42, i love superhero movies \uD83E\uDDB8\u200D\u2642\uFE0F and Christmas is the most wonderful time of the year! \uD83C\uDF84"

原文图片如下:

您使用的字符串无效(我也爱...\n\u2705笑\uD83D\uDE02\n\u2705看小说\uD83D\uDCDA\n\u2705 看电影\uD83C\uDFAC\n\u2705")

它应该是有效的字符串文字 "\\uD83D\\uDCDA\\u2705"

您有一个 JSON 字符串形式的非 BMP 字符字符串。而你的 decodeEmoji 无法将它们转换成有效的字符。

所以我们需要对这样的字符串进行强制转换

extension String {
    var jsonStringRedecoded: String? {
        let data = ("\""+self+"\"").data(using: .utf8)!
        let result = try! JSONSerialization.jsonObject(with: data, options: .allowFragments) as! String
        return result
    }
}

之后你需要使用下面的函数从上面的字符串中解码表情符号。

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

通常JSON解码器可以将这些类型的字符解码成表情符号 可能有无效的机会 JSON

使用前首先需要验证json这些东西是否有效

USAGE:

let jsonDecodedString = "Your string".jsonStringRedecoded
let decodedEmojiText = jsonDecodedString?.decodeEmoji
debugPrint("\(decodedEmojiText)")