如何在Swift 2.0中解码HTML实体? [英] How do I decode HTML entities in swift 2.0?
本文介绍了如何在Swift 2.0中解码HTML实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Stackoverflow上找到了此扩展名.但是,有一个错误.如何解决此错误?
I found this extension on Stackoverflow. However, there was an error. How do I fix this error?
Cannot invoke initializer for type 'NSAttributedString' with an argument list of type '(data: NSData, options: [String : AnyObject], documentAttributes: NilLiteralConvertible, error: NilLiteralConvertible)'
"let attributedString"中出现错误.
Error is in "let attributedString".
extension String {
init(htmlEncodedString: String) {
let encodedData = htmlEncodedString.dataUsingEncoding(NSUTF8StringEncoding)!
let attributedOptions : [String: AnyObject] = [
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding
]
let attributedString = NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil, error: nil)! //ERROR HERE!
self.init(attributedString.string)
}
}
推荐答案
Looking at the docs I believe you have the correct method, but note that Swift 2 has error handling, so you would need to do:
extension String {
init(htmlEncodedString: String) {
do {
let encodedData = htmlEncodedString.dataUsingEncoding(NSUTF8StringEncoding)!
let attributedOptions : [String: AnyObject] = [
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding
]
let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
self.init(attributedString.string)
} catch {
fatalError("Unhandled error: \(error)")
}
}
}
我已经在操场上对其进行了测试,并且可以轻松编译.
I've tested that in a playground and it happily compiles.
这篇关于如何在Swift 2.0中解码HTML实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文