将属性文本转换为 HTML in Swift 4
Convert attributed text to HTML in Swift 4
我正在尝试将属性文本转换为 Swift 4 中的 HTML,以便它可以存储在 Firebase/Firestore 中并在不同的 devices/platforms 之间同步。我已经阅读了在 Whosebug 上可以找到的所有文章,包括 , Convert attributed text to HTML and this blog article: 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)
感谢您的帮助
对于Swift 4.x,行:
let att = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
应该是:
let att = [NSAttributedString.DocumentAttributeKey.documentType: NSAttributedString.DocumentType.html]
我正在尝试将属性文本转换为 Swift 4 中的 HTML,以便它可以存储在 Firebase/Firestore 中并在不同的 devices/platforms 之间同步。我已经阅读了在 Whosebug 上可以找到的所有文章,包括
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]