如何在swift 2.0中解码HTML实体?

0 html swift

我在Stackoverflow上找到了这个扩展.但是,出现了错误.我该如何解决这个错误?

Cannot invoke initializer for type 'NSAttributedString' with an argument list of type '(data: NSData, options: [String : AnyObject], documentAttributes: NilLiteralConvertible, error: NilLiteralConvertible)'
Run Code Online (Sandbox Code Playgroud)

错误在"let attributionString"中.

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

Jos*_*ffy 8

查看文档我相信你有正确的方法,但请注意Swift 2有错误处理,所以你需要这样做:

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)")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我在游乐场测试了它,它很乐意编译.