I am trying to show emojis coming from JSON response. It work fine when we don't have 0️⃣1️⃣3️⃣5️⃣ in below string and does not work with below string.
var titleLabelString = \ud83d\ude0a\ud83d\ude18\u2626\ufe0f 0️⃣1️⃣3️⃣5️⃣
Function I am using:
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
}
}
Using it like:
titleLabelString = titleLabelString.decodeEmoji!
What is wrong in this?
The code points you have shown in the comment:
represents a string like this:
\ud83d\ude0a\ud83d\ude18\ud83d\ude025️⃣3️⃣1️⃣0️⃣
(Seems you have chosen another string than in your question.)
As a valid String literal in Swift, it becomes:
Anyway, you have a string where non-BMP characters are represented with JSON-string like escaped sequence. And your
decodeEmoji
cannot convert them into valid characters.You can forcefully convert such strings:
(If your string may contain some more meta-characters, you may need to modify this code.)
But generally, usual JSON decoder can decode non-BMP characters (including emojis). So, if you get this sort of string from JSON response,
or
You should better check these things before using forced re-decoding.