Swift and Wordpress API: Wordpress API escapes some characters to unicode
Use this extension I wrote for it:
extension String { func htmlDocument() throws -> String { let data = self.data(using: .unicode) let options: [NSAttributedString.DocumentReadingOptionKey: NSAttributedString.DocumentType] = [.documentType : .html] return try NSAttributedString(data: data!, options: options, documentAttributes: nil).string }}
So you can use it in your decoder like:
... name = try container.decode(String.self, forKey: .name).htmlDocument()...
If you need to process such an escaped string in Swift, you can convert it to a normal Unicode string.
So if entering the following code into a Swift playground:
import Foundationfunc convert(escapedString: String) -> String { guard let regex = try? NSRegularExpression(pattern: "(&#([0-9]+);)", options: []) else { return escapedString } let escapedNSString = escapedString as NSString let matches: [NSTextCheckingResult] = regex.matches(in: escapedString, options: [], range: NSMakeRange(0, escapedString.count)) var convertedString = escapedNSString for match in matches.reversed() { let matchString = escapedNSString.substring(with: match.range(at: 2)) var replacement: String if let unicode = UnicodeScalar(Int(matchString)!) { replacement = String(unicode) } else { replacement = "?" } convertedString = convertedString.replacingCharacters(in: match.range, with: replacement) as NSString } return String(convertedString)}let str1 = "Haydarpaşa’da ortaya çıktı! Tam 1700 yıllık…"print (convert(escapedString: str1))let str2 = "Pakistan’da terör saldırısı"print (convert(escapedString: str2))
so you will get as result:
Haydarpaşa’da ortaya çıktı! Tam 1700 yıllık…Pakistan’da terör saldırısı
As per @OOper suggestion better to update title and text where using unicode. swift string is based on the unicode and refer below link of documentation that's proof of swift standard Library or apple's framework handles unicode properly. so your mentioned titles does not make sense … ’
these are numeric character reference, not unicode char.
https://docs.swift.org/swift-book/LanguageGuide/StringsAndCharacters.html