You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

iOS Swift含Emoji字符串解码失败问题求助

Fixing Emoji Decoding for Unicode-Escaped Strings in Swift

Let’s break down why your current decode method isn’t working and get those emojis showing up properly.

The Root Problem

Your existing decodeEmoji() method is designed to reverse the encodeEmoji() process, which converts actual emoji characters into a non-lossy ASCII representation (stored as UTF-8). But the string you’re working with is already a UTF-8 string containing raw Unicode escape sequences (like \u2705 or \uD83D\uDE02), not the output of encodeEmoji(). That’s why decoding it with your current method leaves it unchanged—there’s no non-lossy ASCII data to convert back.

The Solution: Parse Unicode Escape Sequences

We need a custom method that scans the string for \u escape codes and converts them into their corresponding emoji/Unicode characters. Here’s an updated String extension that handles this scenario, plus keeps your original encode/decode for valid use cases:

extension String {
    // Decodes Unicode escape sequences (\uXXXX) into actual characters
    func decodeUnicodeEscapes() -> String {
        let scanner = Scanner(string: self)
        var result = ""
        var tempString: NSString?
        
        while !scanner.isAtEnd {
            // Read all characters until we hit a \u escape
            if scanner.scanUpTo("\\u", into: &tempString), let part = tempString as String? {
                result += part
            }
            
            guard !scanner.isAtEnd else { break }
            
            // Skip the "\u" prefix
            scanner.scanString("\\u", into: nil)
            
            // Read the 4-digit hexadecimal code
            var hexCode: NSString?
            if scanner.scanCharacters(from: .hexadecimal, into: &hexCode), 
               let hex = hexCode as String?, 
               hex.count == 4,
               let code = UInt32(hex, radix: 16),
               let scalar = UnicodeScalar(code) {
                // Convert hex to Unicode scalar and append to result
                result.append(Character(scalar))
            } else {
                // If parsing fails, add the \u back to avoid data loss
                result += "\\u"
                if let invalidHex = hexCode as String? {
                    result += invalidHex
                }
            }
        }
        
        return result
    }
    
    // Original encode method (for converting actual emojis to ASCII-safe escapes)
    func encodeEmojiToASCII() -> String {
        guard let data = self.data(using: .nonLossyASCII, allowLossyConversion: true) else {
            return self
        }
        return String(data: data, encoding: .utf8) ?? self
    }
    
    // Original decode method (for reversing encodeEmojiToASCII)
    func decodeEmojiFromASCII() -> String? {
        guard let data = self.data(using: .utf8) else {
            return nil
        }
        return String(data: data, encoding: .nonLossyASCII)
    }
}

How to Use It

For your specific string, call the new decodeUnicodeEscapes() method instead:

let encodedResponse = "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"

let decodedAboutMe = encodedResponse.decodeUnicodeEscapes()
print(decodedAboutMe)

This will output the string with all emojis rendered correctly, like:

I love too...
✅ Laugh 😂
✅ Read novels 📚
✅ Watch movies 🎬
...and so on

When to Use the Original Methods

Keep encodeEmojiToASCII() and decodeEmojiFromASCII() for cases where you need to convert actual emoji characters into an ASCII-safe format (e.g., storing in a database or sending via an API that doesn’t support raw emojis). For example:

let emojiString = "I love 😂 and 🎬!"
let asciiSafe = emojiString.encodeEmojiToASCII() // "I love \uD83D\uDE02 and \uD83C\uDFAC!"
let decodedBack = asciiSafe.decodeEmojiFromASCII() // "I love 😂 and 🎬!"

内容的提问来源于stack exchange,提问作者Tushar Amkar

火山引擎 最新活动