我正在尝试在 Swift 4 中将属性文本转换为 HTML,以便它可以存储在 Firebase/Firestore 中并在不同的设备/平台之间同步。我已经阅读了在 Stackoverflow 上可以找到的所有文章,包括 Convert attributed string, to, "simple" tagged html , Convert attributed text to HTML和这篇博客文章:http://sketchytech.blogspot.com/2016/02/swift-from-html-to-nsattributedtext-and.html .我发现 Swift 4.x 在各种代码示例(下面的示例)中为 NSDocumentTypeDocumentAttribute 和 NSHTMLTextDocumentType 抛出了一个 Unresolved 标识符错误。这些错误不会在 Swift 3.x 中抛出。 Xcode 建议我可能打算使用 NSDocumentTypeDocumentOption 但不提供修复,我不确定这是否是我想要的或者如果是的话如何使用它。
let myAttributes = [ NSAttributedStringKey.foregroundColor: UIColor.green ]
let attrString = NSAttributedString(string: "Hello.", attributes: myAttributes)
let x = attrString
var resultHtmlText = ""
do {
let r = NSRange(location: 0, length: x.length)
let att = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
let d = try x.data(from: r, documentAttributes: att)
if let h = String(data: d, encoding: .utf8) {
resultHtmlText = h
}
}
catch {
print("utterly failed to convert to html!!! \n>\(x)<\n")
}
print(resultHtmlText)
谢谢你的帮助
最佳答案
对于 Swift 4.x,行:
let att = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
应该是:
let att = [NSAttributedString.DocumentAttributeKey.documentType: NSAttributedString.DocumentType.html]
关于html - 在 Swift 4 中将属性文本转换为 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50126120/