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

标签 html swift

found this extension在计算器上。但是,出现错误。如何修复此错误?

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

错误在“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)
    }
}

最佳答案

查看the docs我相信你有正确的方法,但请注意 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)")
        }
    }
}

我已经在 playground 中对其进行了测试,并且可以顺利编译。

关于html - 如何在 swift 2.0 中解码 HTML 实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32922570/

相关文章:

html - 有没有有效的 html css 规范化器?

swift - 如何在 Firebase 实时数据库中嵌套数据 (Swift)

Swift 任务延续误用;函数多次尝试恢复其继续

ios - 在 Swift iOS 中使用 Objective C 框架的内存泄漏

javascript - 导航栏立即跳转到顶部

javascript - 如何将变量中的字母隔离到它自己的变量中,并在单词长度处停止?

javascript - 使用 Array.from( Array(n) ).map(String) 的 24 小时下拉菜单

html - 使用 DIV 和 CSS

ios - ContactBitMask 指示我的对象发生碰撞,但它们没有

swift - iPad 应用程序的一页上有多个 Tableview