Reputation: 3162
In Swift, I Decoding HTML using NSAttributedString
, see below:
let encodedString = "Phải công nhận rằng kể từ lúc ông Thăng làm bộ trưởng"
let encodedData = encodedString.dataUsingEncoding(NSUTF8StringEncoding)
let attributedOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
let attributedString = NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil, error: nil)
let decodedString = attributedString.string
println(decodedString)
But the result like this:
Phải công nháºn rằng kể từ lúc ông Thăng là m bá»™ trưởng
The true result must be the same with the encodedString
What's wrong in this method?
Upvotes: 3
Views: 2439
Reputation: 539685
You have to specify the used character encoding in the document options:
let encodedString = "Phải công nhận rằng kể từ lúc ông Thăng làm bộ trưởng"
let encodedData = encodedString.data(using: .utf8)!
let attributedOptions : [NSAttributedString.DocumentReadingOptionKey : Any ] = [
.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue ]
do {
let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
let decodedString = attributedString.string
print(decodedString)
} catch {
// error ...
}
// Output: Phải công nhận rằng kể từ lúc ông Thăng làm bộ trưởng
(Updated for Swift 4)
Upvotes: 6