本文介绍了Swift HTML解码问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Swift中,我使用 NSAttributedString 解码HTML,见下:

 <$ c $ 
让encodedData = encodedString.dataUsingEncoding(NSUTF8StringEncoding)
let attributedOptions = [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType]
let attributedString =我的编码 = NSAttributedString(data:encodedData,options:attributedOptions,documentAttributes:nil,error:nil)
let decodeString = attributedString.string
println(decodedString)
pre>

但是结果如下:

真正的结果必须与 encodedString



相同。这种方法有什么问题?

解决方案您必须在文档选项中指定使用的字符编码:

  let encodedString =Phảicôngnhậnrằng 
let encodedData = encodedString.dataUsingEncoding(NSUTF8StringEncoding)!
let encodedData = encodedString.dataUsingEncoding(NSUTF8StringEncoding)!
let attributedOptions:[String:AnyObject] = [
NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute:NSUTF8StringEncoding] //< - ADDED
let attributedString = NSAttributedString(data:encodedData,options :属性选项,documentAttributes:无,错误:无)!
let decodedString = attributedString.string
println(decodedString)
//输出:输出:PhảicôngnhậnrằngkểtừlúcôngThănglàmbộtrưởng

请注意,我必须插入两个unwrap操作符才能使用Xcode 6.1.1进行编译。
您可能希望使用可选绑定来检查结果。



(针对Swift 1.2进行了更新)


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:

The true result must be the same with the encodedString

What's wrong in this method?

解决方案

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.dataUsingEncoding(NSUTF8StringEncoding)!
let attributedOptions : [String : AnyObject ] = [
    NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
    NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding ] // <- ADDED
let attributedString = NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil, error: nil)!
let decodedString = attributedString.string
println(decodedString)
// Output: Phải công nhận rằng kể từ lúc ông Thăng làm bộ trưởng

Note that I had to insert two unwrap operators ! to make it compile with Xcode 6.1.1.You might want to check the results with optional binding instead.

(Updated for Swift 1.2)

这篇关于Swift HTML解码问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 08:01