【发布时间】:2019-03-25 20:23:51
【问题描述】:
我正在尝试在 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 引发了一个未解决的标识符错误。这些错误不会在 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)
感谢您的帮助
【问题讨论】:
标签: html ios swift nsattributedstring